【发布时间】:2011-03-27 05:28:19
【问题描述】:
我的问题是如何让一个线程运行,然后再运行一次,然后再运行一次,然后它会重复自己。
我有一个主文件
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();
}
}
}
}
}
【问题讨论】:
-
您能否尝试以更精确的方式告诉我们您想要完成什么,而不是强迫我们从您的代码中“逆向工程”您的想法?
-
您是否希望您的线程等待较早的线程完成?还是您只是想按顺序触发三个线程而不考虑线程的结果?
-
这是 C# 吗?我不认为 C# 有“同步”或“实现”关键字...这看起来像 Java...
-
呃,你为什么要这么做?线程的全部意义在于一次做不止一件事。
标签: java multithreading loops