问题:给定两个字符数组,char[] c1 = ["1","2","3","4","5"], char[] c2 = ["a","b","c","d","e"],交替打印 1 a 2 b 3 c 4 d 5 e
输出:
1
a
2
b
3
c
4
d
5
e
方式一:LockSupport
private static Thread t1 = null;
private static Thread t2 = null;
public static void main(String[] args) throws InterruptedException {
char[] c1 = "12345".toCharArray();
char[] c2 = "abcde".toCharArray();
t2 = new Thread(() -> {
for (char c : c2) {
LockSupport.park();
System.out.println(c);
LockSupport.unpark(t1);
}
}, "t2");
t1 = new Thread(() -> {
for (char c : c1) {
System.out.println(c);
LockSupport.unpark(t2);
LockSupport.park();
}
}, "t1");
t1.start();
t2.start();
}
方式二:自旋
static volatile int status = 1;
public static void main(String[] args) throws InterruptedException {
char[] c1 = "12345".toCharArray();
char[] c2 = "abcde".toCharArray();
new Thread(() -> {
for (char c : c2) {
// 自旋
while (status != 2) {}
System.out.println(c);
status = 1;
}
}, "t2").start();
new Thread(() -> {
for (char c : c1) {
// 自旋
while (status != 1) {}
System.out.println(c);
status = 2;
}
}, "t1").start();
}
方式三:wait+notify
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
char[] c1 = "12345".toCharArray();
char[] c2 = "abcde".toCharArray();
new Thread(() -> {
synchronized (lock) {
for (char c : c1) {
System.out.println(c);
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}, "t1").start();
Thread.sleep(100);
new Thread(() -> {
synchronized (lock) {
for (char c : c2) {
System.out.println(c);
// 叫醒等待锁队列里的任意一个线程
lock.notify();
try {
// 当前线程进入等待队列,并释放锁
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 必须加,否则程序无法结束,因为无论哪个线程先执行,最后总有一个线程处于wait状态
lock.notify();
}
}, "t2").start();
}
方式四:ReentrantLock - Condition
public static void main(String[] args) throws InterruptedException {
char[] c1 = "12345".toCharArray();
char[] c2 = "abcde".toCharArray();
Lock lock = new ReentrantLock();
// 条件1的锁
Condition condition1 = lock.newCondition();
// 条件2的锁
Condition condition2 = lock.newCondition();
new Thread(() -> {
try {
lock.lock();
for (char c : c1) {
System.out.println(c);
// 叫醒条件2锁
condition2.signal();
try {
// 条件1释放锁,等待
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 叫醒条件2锁
condition2.signal();
} finally {
lock.unlock();
}
}, "t1").start();
Thread.sleep(100);
new Thread(() -> {
try {
lock.lock();
for (char c : c2) {
System.out.println(c);
// 叫醒条件1锁
condition1.signal();
try {
// 条件2释放锁,等待
condition2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 叫醒条件1锁
condition1.signal();
} finally {
lock.unlock();
}
}, "t2").start();
}