【发布时间】:2018-05-04 12:51:11
【问题描述】:
我在核心 java 中工作。我有一个小程序,它将通过相应的线程 thread1 、 thread2 和 thread3 打印数字 1,2,3。
while(true)
{
synchronized (obj)
{
System.out.println("Thread got chance : "+Thread.currentThread().getName());
if (ai.get() ==0 && Thread.currentThread().getName().equalsIgnoreCase("Thread1"))
{
System.out.print(ai.incrementAndGet()+"("+Thread.currentThread().getName()+")"+" ");
obj.notify();
obj.wait();
}
if (ai.get() ==1 && Thread.currentThread().getName().equalsIgnoreCase("Thread2"))
{
System.out.print(ai.incrementAndGet()+"("+Thread.currentThread().getName()+")"+" ");
obj.notify();
obj.wait();
}
if (ai.get() ==2 && Thread.currentThread().getName().equalsIgnoreCase("Thread3"))
{
System.out.print(ai.incrementAndGet()+"("+Thread.currentThread().getName()+")"+" ");
System.out.println("");
ai.set(0);
obj.notify();
obj.wait();
}
}
}
上面的程序逻辑很好并且可以正常工作,即它正在按顺序打印。但是我已经用“Thread got change”打印了线程名称。即我试图确定哪个线程有更多机会运行并知道线程名称 Ex thread 2。
问题是“我怎样才能确保所有线程都获得相同的机会。由于这是小程序,线程将在几毫秒内完成它的工作并出来,我们不会知道。如果线程需要很长时间才能运行”?
请帮忙。
【问题讨论】:
标签: java multithreading concurrency synchronized reentrantlock