Java多线程是否处于活动状态



这样我正在生成线程,但是在for循环之后如何检查所有线程是否都处于活动状态
进一步的过程取决于所有线程
如果线程dead则进行进一步处理

for (int i = 0;i<List.size();i++) {
                if(List.get(i).trim().length() >0 ){
                    Thread thread = new Thread("Thread"+i){
                        public void run(){              
                            threading(List.get(i),ctx,userSesionObj);
                        }
                      };
                      thread.start();
                }
            }
这是我threading函数,它

对我传递的不同数据执行

您可以使用 ExecutorService。事实上,我强烈推荐这个。您可以指定不同的线程行为等。执行程序将为每个提交的线程返回一个 Future 对象,然后您可以循环访问每个Future收集结果。所以以下内容:

for (Future f : futures) {
   f.get(); // get a result here...
}

当所有Futures都返回数据时(即线程完成时),将完成。执行器 API 的工作级别高于 join()/notify() 等,使用起来更安全。

这里有很多功能可以使用,我会推荐教程。

您可能希望join线程。 参看 http://docs.oracle.com/javase/tutorial/essential/concurrency/join.html。 鉴于您可以暂停主线程,也就是说。

使用ExecutorService

- Executors 管理Thread对象并很好地Async任务

- 这里不是直接运行线程的客户端,而是中间对象。

- 将其与返回Future对象submit()方法相结合。

- Future是异步任务的结果。

- 您可以使用具有阻止性质的 Future get() 方法,也可以get()方法与isDone()方法一起使用。

使用 Thread 类中的方法 isAalive

从文档中:

测试此线程是否处于活动状态。如果线程已启动且尚未死亡,则该线程处于活动状态。

正如彼得所建议的,这应该可以...

int count = selectedCategoryList.size();
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < count; i++) {
  if(selectedCategoryList.get(i).trim().length() >0 ){
    final Long CategoryID = Long.parseLong(selectedCategoryList.get(i));
    Thread thread = new Thread("ReplaceMedicationThread"+i){
                          public void run(){              
                            threadingForReplacingMedication(CategoryID,ctx,userSesionObj);
                          }
                    };
    threads.add(thread):
   }
}
//start them in a loop
//join them in a loop
//move on....

在继续处理之前等待某些线程完成的一种简单方法是通过 CompletionService。这是您将如何使用它:

// list of data that need to be processed before continuing execution
List<DataForProcessing> workList = // ...
// An instance of an Executor http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executors.html
Executor exec = // ...
// asume that ResultData is a data structure returned from the processing each
// DataForProcessing instance. If processing does not return a value you could
// parameterise the completion service as CompletionService<Void>.
CompletionService<ResultData> service = new ExecutorCompletionService<ResultData>(executor);
// Submit the tasks for processing. Each task will be processed by the executor and
// its result will be wrapped in a Future and place in a BlockingQueue maintained by
// the CompletionService instance. Again, if your submitted task does not return
// a value you should parameterise your task as Callable<Void>.
for (DataForProcessing data: workList) {
  service.submit(new Callable<ResultData>() {
    public ResultData call() {
      // process the data here and return some result (optionally).
    }
  });
 }
// retrieve the results as the become available.
for (int i = 0; i < workLoad.size(); i++) {
  // Retrieve the next processed result. CompletionService returns each task in a
  // Future which provides you with the means to control the lifecycle of the task.
  // When a submitted task is processed by the executor, its Future is placed on a
  // BlockingQueue maintained by the CompletionService. Invoking take() will return
  // the next available result. If your tasks do not return a result you would still
  // need to call Future<Void> f = service.take() in order to wait for every task
  // to finish before proceeding.
  Future<ResultData> f = service.take();
  // If your task returns some result you may access it via the get() method on the
  // task's Future.
  ResultData result = f.get();
  // do some processing if needed
  process(result);
}

我只是用简单的一个全局 int 参数来完成的。我就是这样做的:

do{
    Thread.sleep(800);
    System.out.println("threadCounter=="+threadCounter);
    }while(threadCounter != 0);

其中threadCounter全局定义int初始化zero

在制作每个线程时,我做 +1 的threadCounter ;

在我的函数中threading在和我做 -1 的threadCounter

在这里Thread.sleep(800)不运行,该 do-while 循环继续。

相关内容

最新更新