0

I use synchronized in order to execute first thread and then execute another when the first thread finished, but both threads are executed at the same time. Why?

public class PrintNums extends Thread {
    int num;

    public PrintNums(int x) {
        this.num = x;  
    }

    @Override
    public void run() {
        this.count();
    }

    public synchronized void count() {
        for (int i = 1; i <= 5; i++) {
            System.out.println((2 * i - this.num));
            try {
                Thread.currentThread().sleep(1000);
            } catch (InterruptedException ex) {
            }
        }
    }

    public static void main(String[] args) {
        PrintNums odd = new PrintNums(1);
        PrintNums even = new PrintNums(0);

        odd.start();
        even.start();
    }
}
Tom
  • 16,842
  • 17
  • 45
  • 54
Tim Mao
  • 27
  • 1
  • 2
    Synchronization is for access to a particular object (ie, synchronization to one object). You have two different objects (`odd` and `even`). – TT. Sep 18 '16 at 10:55
  • 1
    [why this synchronized method is not working as expected?](http://stackoverflow.com/q/26610791) – Tom Sep 18 '16 at 11:03

1 Answers1

2

synchronized without an explicit target means synchronized(this): Each thread is synchronizing on itself, so there's no conflict. If you want to serialize them, you could use synchronized(PrintNums.class).

Note that there is usually a better construct generally than using explicit threads, such as an executor or a latch.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152