本周我开始学习 Java 线程和并发;我需要一些关于我使用 Thread
而不是 Runnable
实现的下一个代码的帮助:
类别
package hilos;
public class Hilo extends Thread {
//Atributos
public static int concurso = 0;
private int veces;
private boolean incrementoDecremento;
//Método constructor
public Hilo(boolean inc, int numeroVeces){
this.incrementoDecremento = inc;
this.veces = numeroVeces;
}
//Método run
@Override
public void run(){
for(int i = 0; i < this.veces; i++){
if(this.incrementoDecremento == true){
concurso++;
System.out.println("La variable introducida es: " + concurso);
}else{
concurso--;
System.out.println("La variable introducida es: " + concurso);
}
}
}
}
主要
package hilos;
public class Usa_Hilos {
public static void main(String[] args) {
int prueba = 5;
Hilo positivo = new Hilo(true, prueba);
Hilo negativo = new Hilo(false, prueba);
positivo.start();
negativo.start();
try{
positivo.join();
negativo.join();
}catch(InterruptedException ex){
System.out.println("Se ha producido un error.");
}
}
}
我的目标是,如果我有两个任务使用相同的值,则两个任务都开始随机递增和递减它,所以基本上它将产生一个由位于 的变量 prueba
确定的随机值Main
类。
问题是,由于某种原因,我一次又一次地进行测试,而我的最终结果始终是零。我使用 synchronized
语句和 Runnable
实现此功能没有任何问题,但使用 Thread
对我来说是不可能的。
最佳答案
尝试大于 5 的数字。您的线程可能运行得太快,以致第一个线程在第二个线程开始之前完成。
10000 证明了这个问题对我来说很好:
public class BadThreads {
public static void main(String[] args) {
MyThread t1 = new MyThread( 10000);
MyThread t2 = new MyThread(-10000);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
System.out.println("interrupted");
}
System.out.println(MyThread.shared);
}
private static class MyThread extends Thread {
public static int shared;
private int change;
public MyThread(int change) {
this.change = change;
}
public void run() {
while (change < 0) {
change++;
shared--;
}
while (change > 0) {
change--;
shared++;
}
}
}
}
结果:
tmp$ javac BadThreads.java && java BadThreads
-8680
...所以我们成功地演示了并发问题。你只跑了 5 次只是“幸运”——或者在你的情况下是不幸的,因为你试图证明这个问题。 :)
关于java - 未能成功演示并发递增/递减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33465899/