我的问题是如何让线程运行,然后在另一次运行之后,然后再次运行,然后它重复自己。
我有一个主文件
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();
}
}
}
}
}
答案 0 :(得分:2)
不是在三个线程之间共享一个锁(在线程释放锁之后哪个线程将在线程上取决于它),而是有三个单独的信号量/锁,其中线程#1为线程解锁一个信号量任务完成后#2,第2个线程解锁第3个线程的信号量,第3个线程解锁线程#1的信号量。
所以它看起来像:
希望这有帮助,
杰森
答案 1 :(得分:0)
您是否考虑过查看Runnable
以确定您拥有的工作块,并考虑使用适当的执行程序来控制何时运行?