everyone. I’ve written a synchronization code in java. There are 2 classes, the first one increases a number by 1000, the second one increses the same number by 10. The process should repeat itself 100 times.
Although I’ve written loop cycles they don’t work.
Here is the code:
public class thread
{
static int count = 100;
public static void main(String[] args)
{
Thread thread1 = new Thread(new XThread());
Thread thread2 = new Thread(new YThread());
thread1.start();
thread2.start();
synchronized(thread2)
{
thread2.notify();
}
}
}
class XThread extends Thread {
static long sum=0;
static int i;
synchronized public void run() {
sum=5+1000;
System.out.println(i+" "+"Thread 1"+" "+sum);
{
for(i= 0; i < lab5.count; i++)
{
try {
{
System.out.println("-----------");
this.wait();
}
}
catch (InterruptedException ex)
{
sum=sum+1000;
System.out.println(i+" "+"Thread 1"+" "+sum);
notify();
}
}
}
}
}
class YThread extends Thread
{
static long sum;
static int i;
synchronized public void run()
{
sum=5+10;
System.out.println(YThread.i+" "+"Thread 2"+" "+YThread.sum);
for(i=0; i < lab5.count; i++)
{
try
{
{
System.out.println("------------");
this.wait();
}
}
catch (InterruptedException ex)
{
sum=sum+10;
System.out.println(YThread.i+" "+"Thread 2"+" "+YThread.sum);
notify();
}
}
}
}
In your code you are calling
waitinrunmethod of your Thread overrides.Unfortunately, nobody calls
notifymethod on the object that is waiting.This is because in your
main, you re-wrapped yourXandYThreadinto genericThreadobject.Because of this a call to
thread2.notify()sends the signal to the wrong object ( not the YThread that is locked, but the wrapper object ).Change the declaration to
Your program still going to lock ( because you are not
notifyingthreads enough times ), but at least it may get further. Noticemayin my last sentence. This is because thenotifyto thread2 may be sent before the thread calls its firstwait.