Synchronized method when using wait ()

I ran the following code:

class Counter extends Thread {

 static int i=0;
//method where the thread execution will start
public void run(){
    //logic to execute in a thread

    while (true) {
        increment();
    }
}

public synchronized void increment()  {
    try {
        System.out.println(this.getName() + " " +  i++);
        wait(1000);
        notify();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
//letโ€™s see how to start the threads
public static void main(String[] args){
    Counter c1 = new Counter();
    Counter c2 = new Counter();
    c1.setName("Thread1");
    c2.setName("Thread2");
    c1.start();
    c2.start();
}
}

As a result of this code, line numbers were added:

1: Thread1 0
2: Thread2 1
3: Thread2 2
4: Thread1 3
5: Thread2 4
6: Thread1 4
7: Thread1 5
8: Thread2 6
stopping...

Since the increment method is synchronized and since it contains wait (1000), I did not expect: 1. Thread2 to print two consecutive fingerprints: lines 2,3 I expected the threads to alternate their fingerprints 2. on lines 5,6, I have 4 .

can someone give me an explanation for this?

+5
source share
3 answers

Synchronized Instance Methods:

public synchronized void foo() { 
    ... 
}

roughly equivalent:

public void foo() {
   synchronized(this) {
       ...
   }
}

Do you see the problem here? Synchronization is performed in the current instance.

Thread, increment , .

( , ), :

private static final Object locker = new Object();

public void foo() {
   synchronized(locker) {
       ...
   }
}

: java - Runnable, Thread.

+9

. Counter increment static, synchronized.

, , .

+1

, , ,

class Counter implements Runnable {

    static int i = 0;
    private Lock lock;
    private Condition condition;

    public Counter(Lock lock, Condition condition) {

        this.lock = lock;
        this.condition = condition;
    }


    public void run() {
        while (true) {
            lock.lock();
            try {
                condition.await(1, TimeUnit.SECONDS);
                System.out.append(Thread.currentThread().getName()).append(" ").println(i++);
                condition.signalAll();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        Lock lock = new ReentrantLock(true);
        Condition condition = lock.newCondition();
        Executor e = Executors.newFixedThreadPool(2);
        e.execute(new Counter(lock, condition));
        e.execute(new Counter(lock, condition));

    }
}
0

All Articles