方法1
public static Thread t1;
public static Thread t2;
public static void main(String[] args) {
char[] cs = {'a','b','c','d'};
int[] is = {1,2,3,4};
CountDownLatch countDownLatch = new CountDownLatch(1);
Object lock = new Object();
t1 = new Thread(()->{
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock) {
for (int i = 0; i < cs.length; i++) {
System.out.println(cs[i]);
try {
lock.notify();
lock.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
lock.notify();
}
},"t1");
t2 = new Thread(()->{
synchronized (lock) {
for (int i = 0; i < is.length; i++) {
System.out.println(is[i]);
countDownLatch.countDown();
try {
lock.notify();
lock.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
lock.notify();
}
},"t2");
t1.start();
t2.start();
}
方法2
public static Thread t1;
public static Thread t2;
public static void main(String[] args) {
char[] cs = {'a','b','c','d'};
int[] is = {1,2,3,4};
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
t1 = new Thread(()->{
lock.lock();
try {
for (int i = 0; i < cs.length; i++) {
System.out.println(cs[i]);
condition2.signal();
condition1.await();
}
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
},"t1");
t2 = new Thread(()->{
lock.lock();
try {
for (int i = 0; i < is.length; i++) {
System.out.println(is[i]);
condition1.signal();
condition2.await();
}
condition1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
},"t2");
t1.start();
t2.start();
}