不废话上代码:
package com.learn.bao.mutithread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class TestGet {
private List<String> list = new ArrayList<String>();
private static CountDownLatch l = new CountDownLatch(2);
public List<String> getList() throws InterruptedException {
synchronized (TestGet.class) {
System.err.println("getList() sleep");
Thread.sleep(5000);
l.countDown();
System.err.println("end getList() sleep");
return list;
}
}
public static synchronized void getNull() {
try {
System.err.println("getNull() sleep");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("end getNull() sleep");
l.countDown();
return;
}
public class Test implements Runnable {
private TestGet t;
private int i;
public Test(TestGet t, int i) {
this.t = t;
this.i = i;
}
@Override
public void run() {
if (i == 0) {
try {
t.getList();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (i == 1) {
TestGet.getNull();
}
}
}
public static void main(String[] args) throws InterruptedException {
TestGet t = new TestGet();
for (int i = 0; i <= 1; i++) {
Thread tr = new Thread(t.new Test(t, i));
tr.start();
}
l.await();
}
}
结果:getList() sleep
end getList() sleep
getNull() sleep
end getNull() sleep
串行的结果,所以可以看出来 synchroized当前class和static方法加上synchroized关键词是一把锁。