I'm trying to print numbers 1-20 with two threads:
- Even thread - Print only even numbers.
- Odd thread - print only odd numbers.
I also have a lock object for synchronization.
My application is stuck. Can you tell me what is the problem?
My code:
public class runIt
{
public static void main(String[] args)
{
Odd odd = new Odd("odd thread");
Even even = new Even("even thread");
odd._t.start();
even._t.start();
try{
odd._t.join();
even._t.join();
}
catch (InterruptedException e){
System.out.println(e.getMessage());
}
}
}
public class Constants{
static Object lock = new Object();
}
public class Even implements Runnable{
Thread _t;
String _threadName;
public Even(String threadName){
_threadName = threadName;
_t = new Thread(this);
}
@Override
public void run(){
for (int i = 0; i < 20; i++){
if (i % 2 == 0){
synchronized (Constants.lock){
try{
Constants.lock.wait();
Constants.lock.notifyAll();
}
catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(_threadName + " " + i + " ");
}
}
}
}
}
public class Odd implements Runnable{
Thread _t;
String _threadName;
public Odd(String threadName){
_threadName = threadName;
_t = new Thread(this);
}
@Override
public void run(){
for (int i = 0; i < 20; i++){
if (i % 2 == 1){
synchronized (Constants.lock){
try{
Constants.lock.wait();
Constants.lock.notifyAll();
}
catch (InterruptedException e1){
e1.printStackTrace();
}
System.out.println(_threadName + " " + i + " ");
}
}
}
}
}
My output should be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Thank you for the assistance, Tam.
Below code will help to someone,
You are misusing
synchronized
andwait
by calling wait on the object you used insynchronized
, immediately, without having a check inside the synchronized block in a loop. NEVER DO THAT AGAIN.In fact here's what happen :
synchronized
line you get a lock onConstants.lock
wait
line, you release the lock onConstants.lock
and wait for a notify from another thread.So what is happening in your prog :
synchronized
and proceed blocking the secondsynchronized
because first has released the lockYou can find the explanation in the site mentioned in package declaraion: Here's the working code:
Everyone on the Stack Overflow tried the same solution. Checkout a different implementation for the same.