[英]Java Thread not work after the Thread.sleep method
我使用下面的代碼來測試多線程,在ThreadDemo的run方法中,我添加了Thread.sleep(milliseconds)方法,但這會導致沒有輸出。 刪除此方法后,它工作正常。 任何人都可以幫助解釋這種行為嗎?
import java.util.concurrent.*;
public class ThreadTest {
private static ThreadLocal<Long> counter = new ThreadLocal<>();
public static void main(String[] args) {
System.out.println("test start");
counter.set(0l);
int count = 3;
ExecutorService executorService = Executors.newFixedThreadPool(count);
for(int i=0;i<count;i++) {
String name = "thread-"+i;
executorService.submit(new ThreadDemo(name,counter));
}
System.out.println("test end");
}
public static class ThreadDemo implements Runnable{
private String name;
private ThreadLocal<Long> counter;
public ThreadDemo(String name, ThreadLocal<Long> counter) {
this.name = name;
this.counter = counter;
}
public void run() {
while(true) {
Long val = (counter.get() == null) ? 1 : ((counter.get()+1)%10);
counter.set(val);
System.out.println("name: "+this.name+" val "+val);
Thread.sleep(10);
}
}
}
}
不要將ThreadLocal
與ExecutorService
一起使用! 將 ThreadLocal 與 ExecutorService 一起使用是否危險?
如果您想存儲數據,請使用其他解決方案來解決您的問題。
另一個問題是,如果您使用Thread::wait(...)
或Thread::sleep(...)
,則需要處理InterruptedException
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
另一個問題是您的線程的名稱,請查看這篇文章: ExecutorService 的命名線程和線程池
僅將線程名稱用於調試,您在ExecutorService
的線程必須是無狀態的。
用
Thread.currentThread().sleep(1000);// time is in milisecond
System.out.println("Test");// here you may know thread is waiting or not
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.