简体   繁体   English

Java:在当前运行时不要启动另一个线程

[英]java: do not start another thread while current alive

I have main thread with method "start". 我有方法“开始”的主线程。 This method starts another thread, that doing long job. 此方法启动另一个线程,该线程需要很长时间。 Method "start" can be call from another threads. 可以从另一个线程调用方法“ start”。 How to avoid creating new threads in "start" method if already have one running and do not lock main thread? 如果已经有一个正在运行并且不锁定主线程,如何避免在“启动”方法中创建新线程? I trying use singleThreadExecutor, but it queues tasks. 我尝试使用singleThreadExecutor,但是它使任务排队。

code: Start method: 代码:启动方法:

 public void start(){
// need only one active thread
// if thread alive, avoid to start another
        t = new Thread( new Runnable() {
            public void run() {
                try {
                    Thread.currentThread().sleep(3000);     
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();      
    }

Simple test 简单测试

    for (int i = 0; i < 100; i++) {
            Thread r = new Thread( new Runnable() {
                public void run() {
                    Helper.getInstance().start();
                }
            });
            r.start();      
   }    

如果只想在当前线程繁忙时丢弃新任务,则可以使用SingleThreadExecutor并将其配置为丢弃所有溢出任务,而不是对其进行排队。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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