[英]Threads in Java
我已经创建了一个简单的程序来测试Java中的Threads。 我想要它无限打印我的数字,如123123123123123.Dunno为什么,但目前它只停止一个周期后完成213。 谁知道为什么?
public class Main {
int number;
public Main(int number){
}
public static void main(String[] args) {
new Infinite(2).start();
new Infinite(1).start();
new Infinite(3).start();
}
}
class Infinite extends Thread {
static int which=1;
static int order=1;
int id;
int number;
Object console = new Object();
public Infinite(int number){
id = which;
which++;
this.number = number;
}
@Override
public void run(){
while(1==1){
synchronized(console){
if(order == id){
System.out.print(number);
order++;
if(order >= which){
order = 1;
}
try{
console.notifyAll();
console.wait();
}
catch(Exception e)
{}
}
else {
try{
console.notifyAll();
console.wait();
}
catch(Exception e)
{}
}
}
try{Thread.sleep(0);} catch(Exception e) {}
}
}
}
每个Infinite
实例都在同步,然后在其自己的console
对象上等待通知。 一旦线程进入console.wait()
,它就不会继续。
你似乎希望它们都在同一个对象上同步 - 所以你需要,例如,使console
静态。
重新阻塞的线程可能等待获取监视器以调用wait。 您没有正确使用等待通知机制。
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#wait%28%29
每个线程正在同一个不同的对象上进行同步。 当控制转到console.wait()时,执行线程将等待另一个线程调用控制对象上的notify()/ notifyAll()。 没有其他线程正在执行此操作,因为每个线程都有自己的控件对象副本。 因此,所有线程在打印一次后无限期地等待。 要解决此问题,请保留所有线程可以等待的公共对象。
请记住, System.out.print(..)
不会自动刷新输出。
另外,看看java.util.concurrent.Semaphore
。 您可能能够执行您正在尝试的操作(按预定义的顺序执行线程),而无需同步和调用等待。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.