可能重複:
Trying to loop 3 threads in a specific order everytime哪有兩個線程訪問同一個對象之一兩種方法陸續在Java
我想從兩個訪問同一個對象的兩種不同的方法線索一個接一個。這裏是我的代碼,
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();
}
}
如果我取消呼叫,而(真),那麼我會期待這樣的輸出,
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();
}
}
鎖定對象可以幫助http://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html – RNJ
燦你編輯你的帖子來解釋_why_你想要做什麼?線程的整個點是異步並行操作。 – Gray
恕我直言,沒有好的/優雅/有效的方式來做到這一點,因爲它是一個壞主意,使用多個線程來執行一個任務,將更簡單和有效地使用一個線程完成的任務。我可以想出很多可怕的方法來用多線程來做到這一點。;) –