我的問題是如何讓一個線程運行,然後在另一個運行之後,然後再運行另一個運行,然後重複自身。試圖按特定順序每次循環3個線程
我有一個主文件
private static ThreadManager threadManager;
public static void main(String[] args)
{
threadManager = new ThreadManager();
}
然後,我有一個ThreadManager類
public class ThreadManager {
public static final Object lock1 = new Object();
public static ConcThread CT = new ConcThread();
public static SocketThread sThread = new SocketThread();
public static PacketThread packetThread = new PacketThread();
public ThreadManager() {
try {
synchronized (lock1) {
packetThread.packetThread.start();
lock1.wait();
CT.concThread.start();
lock1.wait();
sThread.socketThread.start();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
然後,我有3個線程
public class PacketThread implements Runnable {
public Thread packetThread = new Thread(this);
public void run() {
while (true) {
try {
synchronized (ThreadManager.lock1) {
//DoThing1
synchronized (this) {
ThreadManager.lock1.notifyAll();
}
ThreadManager.lock1.wait();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class ConcThread implements Runnable {
public Thread concThread = new Thread(this);
public void run() {
while (true) {
synchronized (ThreadManager.lock1) {
try {
//dothing2
synchronized (this) {
ThreadManager.lock1.notifyAll();
}
ThreadManager.lock1.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public class SocketThread implements Runnable {
public Thread socketThread = new Thread(this);
public void run() {
while (true) {
synchronized (ThreadManager.lock1) {
try {
//dothing3
synchronized (this) {
ThreadManager.lock1.notifyAll();
}
ThreadManager.lock1.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
您可以嘗試以更精確的方式告訴我們您要完成什麼,而不是強迫我們從代碼中「逆向工程」您的想法? – akappa 2011-03-27 05:35:50
你想讓你的線程等待早期線程完成嗎?或者你是否僅僅想連續觸發三個線程,而不管線程的結果如何? – 2011-03-27 05:36:57
這是C#嗎?我不認爲C#有「同步」或「執行」關鍵字...這看起來像Java ... – 2011-03-27 05:40:18