Java 如何使长等待线程运行
我在CoreJava工作。我有一个小程序,它将通过相应的线程thread1、thread2和thread3打印数字1、2、3Java 如何使长等待线程运行,java,multithreading,concurrency,synchronized,reentrantlock,Java,Multithreading,Concurrency,Synchronized,Reentrantlock,我在CoreJava工作。我有一个小程序,它将通过相应的线程thread1、thread2和thread3打印数字1、2、3 while(true) { synchronized (obj) { System.out.println("Thread got chance : "+Thread.currentThread().getName()); if (ai.g
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”打印了线程名称。i、 我试图确定哪个线程有更多的机会运行,并且知道了线程名Ex thread 2
问题是“我如何确保所有线程都获得相同的机会。因为这是一个小程序,线程将在毫秒内完成其工作并出来,我们将不知道。如果一个线程运行时间稍长,该怎么办?”
请提供帮助。
synchronized
不支持fair
策略调用notify()
时,任何等待的线程都可能被唤醒
你可以使用公平的方法:
- 调用
时,等待时间最长的线程将获得锁lock()
- 当您调用时,等待时间最长的线程将首先发出信号
// Use the same lock and condition in different threads
ReentrantLock lock = new ReentrantLock(true); // create a fair lock
Condition condition = lock.newCondition();
while (true) {
lock.lock();
try {
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() + ")" + " ");
condition.signal();
condition.await();
}
if (ai.get() == 1 && Thread.currentThread().getName().equalsIgnoreCase("Thread2")) {
System.out.print(ai.incrementAndGet() + "(" + Thread.currentThread().getName() + ")" + " ");
condition.signal();
condition.await();
}
if (ai.get() == 2 && Thread.currentThread().getName().equalsIgnoreCase("Thread3")) {
System.out.print(ai.incrementAndGet() + "(" + Thread.currentThread().getName() + ")" + " ");
System.out.println("");
ai.set(0);
condition.signal();
condition.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}