重複の可能性:
毎回特定の順序で3つのスレッドをループしようとしています
同じオブジェクトの2つの異なるメソッドに2つのスレッドから次々にアクセスしたいと思います。これが私のコードです、
public class ThreadCoordination
{
private Thread threadSayHello;
private Thread threadSayWorld;
private boolean threadSayWorldStarted = false;
public ThreadCoordination()
{
createThreads();
}
private void createThreads()
{
threadSayWorld = new Thread(new Runnable()
{
public void run()
{
try
{
// while (true)
{
sayWorld();
}
}
catch (InterruptedException ex)
{}
}
});
threadSayHello = new Thread(new Runnable()
{
public void run()
{
try
{
// while (true)
{
sayHello();
if (!threadSayWorldStarted)
{
threadSayWorldStarted = true;
threadSayWorld.start();
}
}
}
catch (InterruptedException ex)
{}
}
});
threadSayHello.start();
}
private synchronized void sayHello() throws InterruptedException
{
System.out.print("Hello ");
}
private synchronized void sayWorld() throws InterruptedException
{
System.out.println("World!");
}
public static void main(String[] args)
{
new ThreadCoordination();
}
}
while(true)の呼び出しのコメントを解除すると、次のような出力が期待されます。
Hello World!
Hello World!
Hello World!
Hello World!
...
どうすればいいのか教えてください。ラジャ。
閉じた投稿を編集できるかどうかわかりません。私が知る限り、解決策を投稿したいだけです。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class SequenceAccess
{
private ReentrantLock myLock;
private Condition ensureSequence;
private int sequenceNo = 1;
public SequenceAccess()
{
myLock = new ReentrantLock();
ensureSequence = myLock.newCondition();
startThreads();
}
private void startThreads()
{
new Thread(new Runnable()
{
public void run()
{
try
{
while (true)
method1();
}
catch (InterruptedException ex)
{}
}
}).start();
new Thread(new Runnable()
{
public void run()
{
try
{
while (true)
method2();
}
catch (InterruptedException ex)
{}
}
}).start();
new Thread(new Runnable()
{
public void run()
{
try
{
while (true)
method3();
}
catch (InterruptedException ex)
{}
}
}).start();
}
private void method1() throws InterruptedException
{
myLock.lock();
try
{
while (sequenceNo != 1)
ensureSequence.await();
sequenceNo = 2;
System.out.println("Method 1");
ensureSequence.signalAll();
}
finally
{
myLock.unlock();
}
}
private void method2() throws InterruptedException
{
myLock.lock();
try
{
while (sequenceNo != 2)
ensureSequence.await();
sequenceNo = 3;
System.out.println("Method 2");
ensureSequence.signalAll();
}
finally
{
myLock.unlock();
}
}
private void method3() throws InterruptedException
{
myLock.lock();
try
{
while (sequenceNo != 3)
ensureSequence.await();
sequenceNo = 1;
System.out.println("Method 3");
ensureSequence.signalAll();
}
finally
{
myLock.unlock();
}
}
public static void main(String[] args)
{
new SequenceAccess();
}
}