-1

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

}
}
dkb
  • 4,389
  • 4
  • 36
  • 54
  • 3
    works fine for me, without any issue prints `test start name: thread-0 val 1 name: thread-1 val 1 test end name: thread-2 val 1 name: thread-2 val 2 name: thread-1 val 2 name: thread-0 val 2 name: thread-1 val 3 name: thread-2 val 3 name: thread-0 val 3` – dkb Mar 06 '19 at 10:19
  • Is it possible related to . environment? It works in my env now. – Lu Ning Mar 07 '19 at 05:17
  • No, it is not related to the environment. – dkb Mar 07 '19 at 05:44

2 Answers2

-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.

rockfarkas
  • 132
  • 2
  • 8
  • I'd go a step further and simply say, "Do not use `ThreadLocal` in new code." IMO, the only reason for it to exist is to let you _cheaply_ re-use older code that depends on `static` variables in a multi-threaded system. New code should avoid anything `static`, and it should avoid sharing objects between threads (except of course for synchronization objects like queues and locks semaphores), and therefore it should not need `ThreadLocal`. – Solomon Slow Mar 06 '19 at 18:42
  • It is not "dangerous" to use a `ThreadLocal` in a thread-pool. It may produce unexpected results but it's not inherently bad. The other are good points but they don't solve the problem. – Gray Mar 06 '19 at 19:17
  • I think the only way to solve the problem is the code refactoring, so my answer helps to solve the problem, the original question does not have a good answer! – rockfarkas Mar 07 '19 at 08:31
  • @Gray : The OP clearly wrote he has problem with the sleep method, so because I had answered the sleep related question, I give a possible solution though. – rockfarkas Mar 07 '19 at 08:38
-4

use

Thread.currentThread().sleep(1000);// time is in milisecond
System.out.println("Test");// here you may know thread is waiting or not
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
vivekdubey
  • 484
  • 2
  • 7
  • 1
    Use it why? What difference will it make? What problem will it solve? Why should the OP go to all the trouble of calling a static method via an instance variable? Please explain your answer. – user207421 Mar 06 '19 at 10:21
  • Thread is not instance variable it is Class and still we are calling static method. Thread.currentThread() will return current running thread and current running thread will sleep as you are expecting. – vivekdubey Mar 06 '19 at 10:26
  • First read with patience ,what I have written ,I have also written we are calling static method from Thread class read you first comment Why should the OP go to all the trouble of calling a static method via an instance variable? In above code we are not using instance variable. – vivekdubey Mar 06 '19 at 10:37
  • Yes I tried your original code,It is working fine on mysystem.Thread.sleep(),Thread.currentThread().sleep() behave same way.For details you can check following link https://stackoverflow.com/questions/2077216/java-thread-currentthread-sleepx-vs-thread-sleepx – vivekdubey Mar 06 '19 at 10:53
  • Your link agrees that your answer is nonsense. Again, please explain why `Thread.currentThread().sleep()` is better than, or even different from, `Thread.sleep()`. It isn't. – user207421 Mar 07 '19 at 04:58
  • First thing your question is non sense if you are arguing so much on Thread.currentThread().sleep() and Thread.sleep(), you should think logically why Program will work after removal of Thread.sleep() and not work with this line,As per java documentation work of sleep method is thread will go in sleep state for given time interval and it will come in runnable state after sleep, it is not going to impact your logic any how. I never said one is better and other is bad ,I said you can try as alternative. you are replying here like non mature developer. – vivekdubey Mar 07 '19 at 07:11
  • Stop changing the subject. My question, for the third time, is why do you think `Thread.sleep()` and `Thread.currentThread().sleep()` are different, when they aren't? You still haven't answered it, and your 'answer' consists of nothing else but this apparent assertion. And if you don't think they are different, why did you change the OP's code? and what *is* your answer? – user207421 Mar 07 '19 at 10:01