线程交替打印
当时线程交替打印问题核心 :主要就是对Java锁的理解和使用,废话不多说上代码
Synchronized 同步锁方式
public class ThreadQuestOne {
//简单计数器
private static int COUNT=0;
//对象锁
private static final Object LOCK=new Object();
public static void main(String[] args) {
syncLock();
}
private static void syncLock() {
new Thread(()->{
while(COUNT<100) {
synchronized(LOCK) {
if ((COUNT&1)==0) {
System.out.println("偶数线程||"+(COUNT++));
}
}
}
}).start();
new Thread(()->{
while(COUNT<100) {
synchronized(LOCK) {
if ((COUNT&1)==1) {
System.out.println("奇数线程||"+(COUNT++));
}
}
}
}).start();
}
}
Notify wait 方式
public class ThreadQuestTWO {
//简单计数器
private static int COUNT=0;
//对象锁
private static final Object LOCK=new Object();
public static void main(String[] args) {
notifyAllMethod();
}
private static void notifyAllMethod(){
Runnable rs= ()->{
while (COUNT<=100) {
synchronized (LOCK) {
System.out.println(Thread.currentThread().getName()+""+(COUNT++));
LOCK.notifyAll();
if ((COUNT&1)==0) {
//阻塞
try {
LOCK.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
};
CompletableFuture.allOf(CompletableFuture.runAsync(rs),
CompletableFuture.runAsync(rs)).join();
}
1.8 JDK CompletableFuture方式
public class ThreadQuestTWO {
//简单计数器
private static int COUNT=0;
//对象锁
private static final Object LOCK=new Object();
public static void main(String[] args) {
CompletableFutureTest();
}
//第三种方式相互隔离的方式
private static void CompletableFutureTest() {
CompletableFuture<Void> cf=CompletableFuture.runAsync(()->{
while (COUNT<100) {
synchronized (LOCK) {
if ((COUNT&1)==0) {
System.out.println("当前偶数线程"+(COUNT++));
}
}
}
});
CompletableFuture<Void> cf1=CompletableFuture.runAsync(()->{
while (COUNT<100) {
synchronized (LOCK) {
if ((COUNT&1)==1) {
System.out.println("当前奇数线程"+(COUNT++));
}
}
}
});
CompletableFuture.allOf(cf,cf1).join();
}