简体   繁体   English

Java Thread 在 Thread.sleep 方法后不起作用

[英]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.我使用下面的代码来测试多线程,在ThreadDemo的run方法中,我添加了Thread.sleep(milliseconds)方法,但这会导致没有输出。 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 !不要将ThreadLocalExecutorService一起使用! Is it dangerous to use ThreadLocal with ExecutorService? 将 ThreadLocal 与 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(...)另一个问题是,如果您使用Thread::wait(...)Thread::sleep(...) ,则需要处理InterruptedException

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另一个问题是您的线程的名称,请查看这篇文章: ExecutorService 的命名线程和线程池

Use thread names for debug only, your threads in ExecutorService must be stateless.仅将线程名称用于调试,您在ExecutorService的线程必须是无状态的。

use

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.

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