Java synchronized method not working

时间:2015-08-14 23:00:34

标签: java multithreading synchronized

I'm trying to figure out what I am doig wrong right here. My plan is to increment a static variable but lock it so only one thread at a time can do that. Here's my code: Test.java

    public class Test implements Runnable {

    private static int NUM=0;
    private static int CURRENT_ID = 0;

    private final int id = Test.CURRENT_ID++;

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

    private synchronized void raise() {
        for( int i=0 ; i<5 ; ++i ) {
            ++Test.NUM;
            System.out.println("["+ this.id +"] " + Test.NUM);
            Thread.yield();
        }
    }
}

Main:

class Main {
    public static void main(String args[]) {
        ExecutorService ex = Executors.newCachedThreadPool();
        for( int i=0 ; i<3 ; ++i ) {
            ex.execute(new Test());
        }
        ex.shutdown();
    }
}

I expect output like from thread 0 increasing, then 1, 2 after that and so on. Instead they're mixed, that means all of them are using variable Test.NUM at the same time, what is totally wrong.

0 个答案:

没有答案