我是多线程新手;这是启动线程的正确方法吗?
if(!sesThread.isAlive()) {
try {
sesThread.start();
}catch(IllegalThreadStateException e) { System.out.println("y u start");}
}
前提:调用者处理字节数组并将其推送到队列。 session 线程将进行双端队列并进一步处理它们,直到队列为空,因此 session 的 run() 返回
问题:我抛出了很多异常,即使如此,由于某种原因,我的 session 线程的 run() 被调用了两次!
即(开始>开始>结束>结束)NOT(开始>结束>开始>结束)
是否有某种方法可以同步或确保这种“延迟实例化”机制调用仅启动一次?
ps。我正在制作一个旨在提高传输速度的多线程 UDP 套接字服务器,因此最好有最小的延迟,而不是在 isAlive() 之前进行一些 thread.sleep()
最佳答案
不,你不应该使用这种机制。
您的消费者线程不应仅仅因为队列为空而终止。线程的启动成本很高。您应该使用 BlockingQueue
并让您的消费者线程在队列为空时阻塞。
public class TwoThreads {
public static void main(String args[]) throws InterruptedException {
System.out.println("TwoThreads:Test");
new TwoThreads().test();
}
// The end of the list.
private static final Integer End = -1;
static class Producer implements Runnable {
final BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 0; i < 1000; i++) {
queue.add(i);
Thread.sleep(1);
}
// Finish the queue.
queue.add(End);
} catch (InterruptedException ex) {
// Just exit.
}
}
}
static class Consumer implements Runnable {
final BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
boolean ended = false;
while (!ended) {
Integer i = queue.take();
ended = i == End;
System.out.println(i);
}
}
}
public void test() throws InterruptedException {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
Thread pt = new Thread(new Producer(queue));
Thread ct = new Thread(new Consumer(queue));
// Start it all going.
pt.start();
ct.start();
// Wait for it to finish.
pt.join();
ct.join();
}
}
关于java 使用 isAlive() 启动一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29095250/