public class SynchronizedTest {

    public static void main(String[] args) {
        SynchronizedTest synchronizedTest = new SynchronizedTest();
        for (int i = 0; i < 5; i++) {
            int thisi = i;
            Thread thread = new Thread(() -> {
                if (thisi % 2 == 0) {
                    synchronizedTest.testSynchronizedMethod1();
                } else {
                    synchronizedTest.testSynchronizedMethod2();
                }
            });
            thread.start();
        }
    }

    public synchronized void testSynchronizedMethod1() {
        System.out.printf("%s-testSynchronizedMethod1-start-count=%s\n", Thread.currentThread().getName(), count);
        count ++;
        System.out.printf("%s-testSynchronizedMethod1-end-count=%s\n", Thread.currentThread().getName(), count);
    }

    public synchronized void testSynchronizedMethod2() {
        System.out.printf("%s-testSynchronizedMethod2-start-count=%s\n", Thread.currentThread().getName(), count);
        count ++;
        System.out.printf("%s-testSynchronizedMethod2-end-count=%s\n", Thread.currentThread().getName(), count);
    }
}

  

posted @ 2021-08-13 11:49  步江伍德  阅读(20)  评论(0)    收藏  举报