我在核心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“。也就是说,我试图确定哪个线程有更多的运行机会,并知道了线程名称ExThread2。
问题是“我如何确保所有的线程都有相同的机会。因为这是一个小程序,线程会在毫秒内完成工作并出来,我们不会知道。如果一个线程花了很长的时间运行呢?”
请帮帮忙。
发布于 2018-05-04 21:17:09
synchronized
不支持fair
策略。当你调用notify()
时,任何等待的线程都会被唤醒。
您可以使用公平的ReentrantLock
lock()
时,等待时间最长的线程将获得锁。signal()
时,将首先向等待时间最长的线程发出信号。以下是示例代码:
// 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();
}
}
https://stackoverflow.com/questions/50175413
复制相似问题