Trying to loop 3 threads in a specific order everytime
My question is how do I make a thread run, then after that another run, then after that another run again, then it repeats itself.
I have a main file
private static ThreadManager threadManager;
public static void main(String[] args)
{
threadManager = new ThreadManager();
}
Then I have a ThreadManager class
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();
开发者_如何学Go sThread.socketThread.start();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Then I have 3 threads
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();
}
}
}
}
}
Rather than having a single lock shared between the three threads (which is in-determinant on which thread will pick up after a thread releases the lock), have three separate semaphore/locks, where thread #1 unlocks a semaphore for thread #2 after its task is complete, thread #2 unlocks the semaphore for thread #3, and thread #3 unlocks the semaphore for thread #1.
So it would look something like:
- Thread #1 runs (thread #2 and thread #3 are currently blocked)
- Thread #1 completes
- Thread #1 unlocks semaphore for thread #2
- Thread #1 blocks
- Thread #2 runs
- Thread #2 completes
- Thread #2 unlocks semaphore for thread #3
- Thread #2 blocks
- Thread #3 runs
- Thread #3 completes
- Thread #3 unlocks semaphore for thread #1
- Thread #3 blocks
Hope this helps,
Jason
Have you considered looking at Runnable
to identify the chunks of work you have, and an appropriate Executor to control what runs when?
精彩评论