我使用下面的代码测试多线程,在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);
}
}
}
}
答案 0 :(得分:-1)
Do not use ThreadLocal
with ExecutorService
!
Is it dangerous to use ThreadLocal with ExecutorService?
If you want store data, use another solution to your problem.
Another problem is you need handle InterruptedException
if you use Thread::wait(...)
, or Thread::sleep(...)
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Another issue is the name of your Thread, check this article: Naming threads and thread-pools of ExecutorService
Use thread names for debug only, your threads in ExecutorService
must be stateless.
答案 1 :(得分:-3)
使用
Thread.currentThread().sleep(1000);// time is in milisecond
System.out.println("Test");// here you may know thread is waiting or not