[Re-posted as
multi threading in java[
^] — SA]
i have 2 threads..
thread1 is started and calls thread2 to perform task
once thread2 is finished, notify thread1
thread1 receives thread2 notification..
thread1 requests another task to thread2
thread2 performs it and notifies thread1 once its done
thread1 receives notification and requests another task to thread2
and so on..
how will i do this in java?
thanks,
Questioner added:
package testpackage;
import java.util.Date;
public class Main {
private static class MyThreadClass extends Thread {
private final boolean shouldWait;
private final Object someSharedResource;
public MyThreadClass(final Object someSharedResource, final boolean shouldWait) {
this.someSharedResource = someSharedResource;
this.shouldWait = shouldWait;
}
public void run() {
while(PerformTask());
}
public boolean PerformTask()
{
final String name = Thread.currentThread().getName();
System.out.println("Thread " + name + " is running at " + new Date());
if (shouldWait) {
System.out.println("Thread " + name + " is waiting for sharedResource to be notified... at " + new Date());
synchronized(someSharedResource) {
try {
someSharedResource.wait();
System.out.println("Thread " + name + " was woken up at " + new Date());
}
catch(InterruptedException e) {
System.out.println("Thread " + name + " was interrupted!");
}
}
}
try {
Thread.sleep(2000);
}
catch(InterruptedException e) {
}
System.out.println("Thread " + name + " is done at " + new Date());
synchronized(someSharedResource) {
someSharedResource.notifyAll();
}
return true;
}
}
public static void main(String[] args) throws Exception {
final Object sync = new Object();
final MyThreadClass t1 = new MyThreadClass(sync, true);
final MyThreadClass t2 = new MyThreadClass(sync, false);
t1.setName("thread1");
t1.start();
t2.setName("thread2");
t2.start();
}
}
this code outputs:
Thread thread1 is running at Mon Aug 12 13:39:50 SGT 2013
Thread thread1 is waiting for sharedResource to be notified... at Mon Aug 12 13:39:50 SGT 2013
Thread thread2 is running at Mon Aug 12 13:39:50 SGT 2013
Thread thread2 is done at Mon Aug 12 13:39:52 SGT 2013
Thread thread2 is running at Mon Aug 12 13:39:52 SGT 2013
Thread thread1 was woken up at Mon Aug 12 13:39:52 SGT 2013
Thread thread1 is done at Mon Aug 12 13:39:54 SGT 2013
i want the output to be:
Thread thread1 is running at Mon Aug 12 13:39:50 SGT 2013
Thread thread1 is waiting for sharedResource to be notified... at Mon Aug 12 13:39:50 SGT 2013
Thread thread2 is running at Mon Aug 12 13:39:50 SGT 2013
Thread thread2 is done at Mon Aug 12 13:39:52 SGT 2013
Thread thread1 was woken up at Mon Aug 12 13:39:52 SGT 2013
Thread thread1 is done at Mon Aug 12 13:39:54 SGT 2013
Thread thread2 is running at Mon Aug 12 13:39:52 SGT 2013
how will i do this? thanks