我正在自学 Java,我想了解多线程。我创建MyThread
了一个带有作业的类来执行循环,直到条件为真,然后打印有关它的信息。它包含静态字段left
,该字段在构造函数中递增,并在作业完成时递减。类Flag
是“告诉”线程何时开始。不幸的是,当所有线程都完成时left
不等于零。我做了一些方法synchronized
,它变得更好了,但它仍然不完美。我究竟做错了什么?
import java.util.Random;
class Flag
{
private boolean ok = false;
synchronized boolean ok()
{
return ok;
}
synchronized void setOk(boolean ok)
{
this.ok = ok;
}
}
class MyThread extends Thread
{
static int left = 0;
synchronized void add()
{
left++;
}
synchronized int remove()
{
return --left;
}
String name;
Flag flag;
Random rnd = new Random();
public MyThread(String name, Flag flag)
{
this.name = name;
this.flag = flag;
add();
}
public void run()
{
while(!flag.ok());
double rnd;
long count = 0;
do{
count++;
rnd = Math.random();
} while(rnd > 0.00001);
print(count);
}
synchronized void print(long count)
{
System.out.printf("%s %10d left: %3d%n", name, count, remove());
}
}
public class Test
{
public static void main(String... args) throws Exception
{
Flag flag = new Flag();
for(int i=0; i<2000; i++){
new MyThread(String.format("%04d",i),flag).start();
}
flag.setOk(true);
}
}