简体   繁体   中英

Java Thread not work after the Thread.sleep method

I used below code to test multi-thread, in the run method of ThreadDemo, I added Thread.sleep(milliseconds) method, but this will cause no output. After removing this method, it works fine. Anybody can help explain this behavior?

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);
        }
    }

}
}

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.

use

Thread.currentThread().sleep(1000);// time is in milisecond
System.out.println("Test");// here you may know thread is waiting or not

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM