Hello Members,
I am trying to solve the following problem using threads:
Thread_1 outputs values from 1 to 1000. Thread_1 waits. Thread_2 outputs values from 1 to 1000. Thread_2 now waits. Thread_1 outputs values from 1000 to 2000. Thread_1 is done. Thread_2 outputs values from 1000 to 2000. Thread_1 exits followed by Thread_2.
I have the following program where I use a Lock to ensure only one thread is in the critical section. What I am having trouble with is switching between threads as mentioned in the previous paragraph. Any help would be much appreciated.
Thank you!
The Lock Class:
public class Lock{
private boolean isLocked = false;
public synchronized void lock() throws InterruptedException{
while(isLocked){
wait();
}
isLocked = true;
}
public synchronized void unlock(){
isLocked = false;
notify();
}
}
The Thread Class and the main program:
class Share extends Thread
{
private static Lock lock = new Lock();
Share(String threadname)
{
super(threadname);
}
public synchronized void print(int start, int end)
{
for(int i = start; i<=end;i++)
{
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
public synchronized void run()
{
try{
lock.lock();
}
catch (InterruptedException e){}
try{
lock.lock();
}
catch (InterruptedException e){}
lock.unlock();
}
}
public class SynThread1
{
public static void main(String[] args)
{
Share t1=new Share("One");
t1.start();
Share t2=new Share("Two");
t2.start();
}
}