Sunny Gupta
Sunny Gupta

Reputation: 7067

Creating Two Threads by passing the same instance of Runnable

Thread runnableInst = new Runnable(){  public void run(){}};

Thread thread1 = new Thread(runnableInst);
Thread thread2 = new Thread(runnableInst);

thread1.start();
thread2.start();

Is it fine to start two thread on the same Object runnableInst ?

Is it good to make this kind of design?

Upvotes: 1

Views: 722

Answers (4)

ShashiS
ShashiS

Reputation: 11

Is it fine to start two thread on the same Object runnableInst ?

Yes, it is fine to start two threads on the same Object runnableInst.

Is it good to make this kind of design -- it depends on the use case. For example, if there is nothing related to a read/write on a shared resource, then this is a good design.

Upvotes: 0

Steve McLeod
Steve McLeod

Reputation: 52448

It is indeed possible. I don't think it is fine or good design in most situations. I like to consider a Runnable instance to be an isolated piece of code that only shares data with other threads through well-defined, safe ways.

Upvotes: 0

Nick
Nick

Reputation: 25799

Yes, you can do this but one thing to watch is that both threads will be accessing the instance data of the runnableInst. So you will have to make sure that access is synchronised where necessary.

Upvotes: 2

Marko Topolnik
Marko Topolnik

Reputation: 200148

There's no problem with doing that. However, if you plan on dispatching a lot of parallel tasks, you might want to start using the ExecutorService API.

Upvotes: 1

Related Questions