java . 上锁

import org.testng.annotations.Test;

public class SynchronizedTest {

public synchronized void test() {
    System.out.println("test开始.........");
    try {
        Thread.sleep(1);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("test结束!!!!!!!!!!");
}



public  void test2() {
    synchronized (SynchronizedTest.class) {
        System.out.println("test2开始.........");
        try {
            Thread.sleep(1000);

        } catch (InterruptedException e) {
            System.out.println(e);
            e.printStackTrace();
        }
        System.out.println("test2结束.........");
    }
}

}

结果
test开始.........
test开始.........
test开始.........
test结束!!!!!!!!!!
test结束!!!!!!!!!!
test结束!!!!!!!!!!

================

test2开始.........
test2结束.........
test2开始.........
test2结束.........
test2开始.........
test2结束.........

Process finished with exit code 0

你可能感兴趣的:(java . 上锁)