I'm trying to create two threads, one thread display even integers from 0 to 10, one thread display odd integers from 1 to 11. Is the following code suitable for designing this program?
public class Mythread {
public static void main(String[] args) {
Runnable r = new Runnable1();
Thread t = new Thread(r);
t.start();
Runnable r2 = new Runnable2();
Thread t2 = new Thread(r2);
t2.start();
}
}
class Runnable2 implements Runnable{
public void run(){
for(int i=0;i<11;i++){
if(i%2 == 1)
System.out.println(i);
}
}
}
class Runnable1 implements Runnable{
public void run(){
for(int i=0;i<11;i++){
if(i%2 == 0)
System.out.println(i);
}
}
}
Pretty much all that is necessary if you are asked to print even odd numbers in synchronized manner.
Below is the code which uses lock on a shared object which has the number to be printed. It guarantees the sequence also unlike the above solution.
The output will look like: t1--1 t2--2 t1--3 t2--4 t1--5 t2--6 t1--7 t2--8 t1--9 t2--10 done t2 done t1
Concurrent Package:
@aymeric answer wont print the numbers in their natural order, but this code will. Explanation at the end.
In order to achieve so, the run methods of the two threads above have to be called one after the other, i.e. they need to be synchronized and I am achieving that using locks.
The code works like this: t1.run prints the odd number and notifies any waiting thread that it is going to release the lock, then goes into a wait state.
At this point t2.run is invoked, it prints the next even number, notifies other threads that it is about to release the lock it holds and then goes into wait state.
This continues till the itr in t2.run() reaches 50, at this point our goal has been achieved and we need to kill these two threads.
By breaking, I avoid calling lock.wait() in t2.run and t2 thread is thus shutdown, the control will now go to t1.run since it was waiting to acquire the lock; but here itr value will be > 51 and we will come out of its run(), thus shutting down the thread.
If break is not used in t2.run(), though we will see numbers 1 to 50 on the screen but the two threads will get into a deadlock situation and continue to be in wait state.