我在下面的代码测试多线程中,在threaddemo的运行方法中,我添加了thread.sleep.sleep(毫秒)方法,但这不会导致输出。删除此方法后,它可以正常工作。有人可以帮助解释这种行为吗?
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
一起使用!使用turelocal与执行人员服务?
如果您想要存储数据,请对您的问题使用另一种解决方案。
另一个问题是,如果使用Thread::wait(...)
或Thread::sleep(...)
InterruptedException
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
另一个问题是线程的名称,请检查本文:命名命名线程和螺纹池
仅对调试使用线程名称,您的线程ExecutorService
必须无状态。
使用
Thread.currentThread().sleep(1000);// time is in milisecond
System.out.println("Test");// here you may know thread is waiting or not