Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Monitor {
- int count = 0;
- public synchronized void aa(int n){
- while (n > 0){
- try {
- count++;
- wait();
- n--;
- }catch (InterruptedException e){}
- }
- System.out.println("count before="+count);
- notifyAll();
- System.out.println("count after="+count);
- }
- public static void main(String[]args){
- Monitor m = new Monitor();
- Thread t1 = new T(2, m);
- Thread t2 = new T(1, m);
- Thread t3 = new T(0, m);
- try{
- t1.start();
- t2.start();
- t3.start();
- } catch (Exception e){}
- }
- }
- class T extends Thread {
- private Monitor m;
- public int par;
- public T(int par, Monitor m){
- this.m = m;
- this.par = par;
- }
- @Override
- public void run() {
- m.aa(par);
- }
- }
- t1 -> count++ (count is now 1), wait()
- t2 -> count++ (count is now 2), wait()
- t3 -> notifyAll() -> t2 wakes up.
- t2 -> notifyAll() -> t1 wakes up
- t1 -> count++ (count is now 3), wait().
- count before=2
- count after=2
- count before=2
- count after=2
- public class Monitor {
- int count = 0;
- public synchronized void aa(int n){
- while (n > 0){
- try {
- count++;
- wait();
- n--;
- }catch (InterruptedException e){}
- }
- System.out.println("count before="+count);
- notify();
- System.out.println("count after="+count);
- }
- public static void main(String[]args){
- Monitor m = new Monitor();
- Thread t1 = new T(2, m);
- Thread t2 = new T(1, m);
- Thread t3 = new T(0, m);
- try{
- t1.start();
- t2.start();
- t3.start();
- } catch (Exception e){}
- }
- }
- class T extends Thread {
- private Monitor m;
- public int par;
- public T(int par, Monitor m){
- this.m = m;
- this.par = par;
- }
- @Override
- public void run() {
- m.aa(par);
- }
- }
- t1 -> count++ (count is now 1), wait()
- t2 -> count++ (count is now 2), wait()
- t3 -> notify() -> t1 wakes up.
- t1 -> count++ (count is now 3) wait().
- count before=2
- count after=2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement