[英]How to run three threads simultaneously with different sleep time in a while loop?
我想在一個具有不同等待時間的while循環中同時運行三個不同的線程。 這是我的示例代碼。
static void someFunction(){
while(true){
Thread t1 = new Thread(){
public void run(){
System.out.println("Thread 1");
try {
Thread.currentThread();
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Thread t2 = new Thread(){
public void run(){
System.out.println("Thread 2");
try {
Thread.currentThread();
Thread.sleep(7000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Thread t3 = new Thread(){
public void run(){
System.out.println("Thread 3");
try {
Thread.currentThread();
Thread.sleep(8000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
}
是否可以在while循環中同時運行三個線程? 還有其他方法可以實現嗎?
預期輸出:線程1線程2線程3線程1(5秒后)線程2(7秒后)線程3(8秒后)
您不能從線程的run()
方法(或它的run()
方法調用的代碼run()
外部控制線程中的run()
。 外循環不是您想要做的方式。 它只會無休止地生成新線程。
由於除了消息和延遲之外,線程是相同的,因此這是將這些數據轉換為變量並具有單個代碼的理想情況:
public class MyThread extends Thread {
private final long interval;
private final String message;
public MyThread(long interval, String message) {
this.interval = interval;
this.message = message;
}
@Override
public void run() {
while (!isInterrupted()) {
System.out.println(message);
try {
sleep(interval);
} catch (InterruptedException e) {
return;
}
}
}
}
請注意,我已將while(true)
替換為while(!isInterrupted())
。 這是給您一種有序終止線程的方法:只需中斷它們即可。
您將使用的方式可能是:
static Thread t1, t2, t3;
static void someFunction() {
t1 = new MyThread(5000, "Thread 1");
t2 = new MyThread(7000, "Thread 2");
t3 = new MyThread(8000, "Thread 3");
// now start them all
t1.start();
t2.start();
t3.start();
}
當您希望線程結束時,只需調用:
t1.interrupt();
t2.interrupt();
t3.interrupt();
您可能還想研究使用ThreadGroup
。 這是一種將線程集合作為(一組!)單個組來處理的便捷方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.