方法1:ロック+コンディション
package com.example.springboot.demo.juc;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test1 {
//volatile 保证isNum线程间可见
private static volatile boolean isNum = true;
private Lock lock = new ReentrantLock();
private Condition num = lock.newCondition();
private Condition cha = lock.newCondition();
public void printNum(int[] nums){
try {
lock.lock();
for (int i = 0; i < nums.length;i++) {
while (isNum) {
System.out.print(nums[i]);
isNum = false;
}
TimeUnit.MILLISECONDS.sleep(300);
cha.signalAll(); //通知打印字母线程
num.await(); //打印数字线程等待
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void printCha(char[] letters){
try {
lock.lock();
for (int i = 0; i < letters.length;i++) {
char letter = letters[i];
while (!isNum) {
System.out.print(letter);
isNum = true;
}
TimeUnit.MILLISECONDS.sleep(300);
num.signalAll(); //通知打印数字线程
cha.await(); //打印字母线程等待
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public static void main(String[] args) {
Test1 test1 = new Test1();
int[] nums = new int[26];
for(int i = 0 ; i<26;i++){
nums[i] = i+1;
}
char[] letters = new char[26];
for(int i = 0 ;i < 26;i++){
letters[i] = (char)('a'+i);
}
new Thread(()->{
test1.printNum(nums);
}).start();
new Thread(()->{
test1.printCha(letters);
}).start();
}
}
方法2:同期+待ち時間+ notity
package com.example.demo.test;
public class Test1 {
public static void main(String[] args) {
final Object object = new Object();
char[] num = "123456789".toCharArray();
char[] cha = "abcdefghi".toCharArray();
new Thread(()->{
synchronized (object){
for (char a : num){
System.out.print(a);
try {
object.notify();
object.wait(); //释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
object.notify(); //必须notify,否则一定又一个线程阻塞
}
}).start();
new Thread(()->{
synchronized (object){
for (char b : cha){
System.out.print(b);
try {
object.notify();
object.wait(); //释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
object.notify(); //必须notify,否则一定又一个线程阻塞
}
}).start();
}
}
方法3:LockSupport
package com.example.demo.test;
import java.util.concurrent.locks.LockSupport;
public class Test2 {
static Thread t1 = null;
static Thread t2 = null;
public static void main(String[] args) {
char[] num = "123456789".toCharArray();
char[] cha = "abcdefghi".toCharArray();
t1 = new Thread(()->{
for (char a : num){
System.out.print(a);
LockSupport.unpark(t2); //叫醒t2
LockSupport.park(t1); //t1阻塞
}
});
t2 = new Thread(()->{
for (char b : cha){
LockSupport.park(t2); //t2阻塞
System.out.print(b);
LockSupport.unpark(t1); //叫醒t1
}
});
t2.start();
t1.start();
}
}