Processor class -
public class Processor extends Thread {
private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
private void doJob1() {
synchronized (lock1) {
System.out.println(Thread.currentThread().getName() + " doing job1");
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName() + " completed job1");
}
}
private void doJob2() {
synchronized (lock2) {
System.out.println(Thread.currentThread().getName() + " doing job2");
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName() + " completed job2");
}
}
public void run() {
doJob1();
doJob2();
}
}
Main method -
final Processor processor1 = new Processor();
final Processor processor2 = new Processor();
processor1.start();
processor2.start();
Here on first run either Thread-0 or Thread-1 takes a lock of job1() and the other sits idle for 5 seconds.
After the first thread releases the lock on job1() and locks job2(), the second thread takes a lock on job1().
I want that the second thread should not sit idle and since job1() is locked by first thread, it should instead lock job2() and then lock job1().
How to do so?
Note: This is the basic blue print. In reality I want my code to work even if there are a 100 tasks and 5 threads.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…