srk
srk

Reputation: 5126

How to execute two threads Sequentially in a class

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

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?

Upvotes: 1

Views: 7782

Answers (4)

assylias
assylias

Reputation: 328598

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.

EDIT

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

Upvotes: 3

Hugues
Hugues

Reputation: 365

I read your question very quickly but what you probably need is join() Have you looked at the Java Concurrency Tutorial ? http://docs.oracle.com/javase/tutorial/essential/concurrency/join.html

Upvotes: 1

mre
mre

Reputation: 44240

Thread#join, although I prefer to use the classes found within the java.util.concurrent package.

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234795

You can use a ThreadPoolExecutor with a SynchronousQueue. This is described in the docs for ThreadPoolExecutor.

Upvotes: 0

Related Questions