Reputation: 30
I am trying to understand the way of how to implement threads in java.
Right now I know that you can use the interface runnable
with the run method to implement Threads.
But what if I want to have two different threads of the same class, which run different methods of this class? I can only override the run method once, so do I have to make a distinction of for example the name of the thread in order to run the right method?
public class PrintState {
private int state = 0;
public synchronized void printNewState() throws InterruptedException {
wait();
System.out.println(state);
}
public synchronized void setValue(int v) {
state = v;
notify();
System.out.println("value set");
}
}
I want to have two Threads which run the methods printNewState()
and setValue(12)
simultaneously, each one in a different thread.
How do I implement the run()
method and the threads in a main-method in order to achieve this?
The result later should be:
value set
12
Upvotes: 0
Views: 1436
Reputation: 30285
But what if I want to have two different threads of the same class, which run different methods of this class? I can only override the run method once, so do I have to make a distinction of for example the name of the thread in order to run the right method?
You need to distinguish between threads of execution and the code being executed. You can have a single Runnable
with a single run()
, and have 1000 threads execute that Runnable
. That means that you have 1000 threads executing the same code, although you could have just a single Runnable
instance for all of them.
I want to have two Threads wich run the methods printNewState() and setValue(12) simultaneously, each one in a different thread.
You could do something like this. Note I'm using lambdas to create the Runnables
:
PrintState ps = new ...
Thread t1 = new Thread(ps::printNewState); //t1 will call printNewState
Thread t2 = new Thread(() -> ps.setValue(12)); //t2 will call setValue(12)
t1.start();
t2.start();
Upvotes: 2