多線程循環(huán)打印A&B
public class MultiThreadPrint {
private static ReentrantLock lock = new ReentrantLock();
private static Condition conditionA = lock.newCondition();
private static Condition conditionB = lock.newCondition();
static void printA() {
for(int i = 0; i< 1000; i++){
try {
lock.lock();
System.out.println("print A");
//synchronize使用wait notify阻塞和喚醒壁却,lock使用await&signal
conditionB.signal();
conditionA.await();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
static void printB() {
for (int i = 0; i < 1000; i++){
try {
lock.lock();
System.out.println("print B");
conditionA.signal();
conditionB.await();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
new Thread(() -> {
printA();
}).start();
new Thread(() -> {
printB();
}).start();
}
單例模式-靜態(tài)內部類
public class Singleton {
//私有構造方法
private Singleton() {
}
//靜態(tài)內部類能保證沒被調用時,不被初始化
private static class SingletonInner {
private static final Singleton singleton = new Singleton();
}
//線程安全
public static Singleton getSingleton() {
return SingletonInner.singleton;
}
}
雙重校驗
public class Singleton {
//私有構造方法
private Singleton() {
}
// volatile防止指令重排
private static volatile Singleton singleton = null;
public static Singleton getSingleton() {
//double-check
if(singleton == null){
synchronized(Singleton.class){
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}