如何在类中顺序执行两个线程 [英] How to execute two threads Sequentially in a class

查看:154
本文介绍了如何在类中顺序执行两个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究java中的线程编程,我遇到了一个问题,我必须一个接一个地执行2个线程。下面是简要抽象我的问题的代码片段。

I'm working on thread programming in java and i was stuck with a problem where i have to execute 2 threads one after another. Below is the code snippet that abstracts my problem in brief.

class A{
  //default execute method of this class
  String a="thread1";
  String b="thread2";
  public void execute(){
    if(a=="thread1"){
       CreateThread1 t1 = new CreateThread1(this);
       t1.call();
    }
    else if(b=="thread2") {
      CreateThread1 t2 = new CreateThread1(this);
       t2.call();
    }
  }//end of execute
  public void UpdateUI(){
    try{
      Display.getDefault.asyncExec(new Runnable(){
        public void run(){
            //ui update code here
        }
      });
    }
    catch(SWTException e){
    }
  }   
}

Class CreateThread1{
    private A object;
    public CreateThread1(A object){
      this.object=object
    }
    public void call(){
      Thread t = new Thread(this);
      t.start();
    }
    public void run(){ 
      //business logic here 
       object.UpdateUI();//updates UI 
    }
}

这里的A类是User Interface类,它显示Thread任务的进度,在上面的代码中CreateThread1启动和CreateThread2即使CreateThread1没有被杀死也会启动,我希望只有在CreateThread1完成任务后才能触发CreateThread2。这可能吗?有什么想法?

Here class A is User Interface class which shows progress of the Thread task, in the above code CreateThread1 starts and CreateThread2 also starts even if CreateThread1 is not killed, i wish CreateThread2 to be triggered only after CreateThread1 finishes its task completely.Is it possible? Any ideas?

推荐答案

你可以使用 FixedThreadPool ,大小为1这将保证顺序执行。

You could use a FixedThreadPool with a size of 1. This will guarantee sequential execution.

ExecutorService executor = Executors.newFixedThreadPool(1);
executor.submit(runnable1);
executor.submit(runnable2);
executor.shutdown();
executor.awaitTermination(10, TimeUnit.SECONDS); //waits until both runnables have finished.

编辑

ExecutorService在内部使用同步结构,因此您可以安全地假设runnable1将在runnable2之前运行。

ExecutorService uses synchonrized structures internally so you can safely assume that runnable1 will run before runnable2.

这篇关于如何在类中顺序执行两个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆