方法一:使用LockSupport
public static Thread t1=null,t2=null;
public static void main(String[] args){
char[] chars = "123456".toCharArray();
char[] chars2 = "ABCDEF".toCharArray();
t1 = new Thread(() -> {
for (char c: chars){
System.out.println(c);
LockSupport.unpark(t2);
LockSupport.park();
}
},"t1线程");
t2 = new Thread(() -> {
for (char c: chars2){
LockSupport.park();
System.out.println(c);
LockSupport.unpark(t1);
}
},"t2线程");
t1.start();
t2.start();
}
方法二,notify,wait
public static void main(String[] args){
final Object o= new Object();
char[] chars = "123456".toCharArray();
char[] chars2 = "ABCDEF".toCharArray();
new Thread(()->{
synchronized (o){
for (char c: chars){
System.out.println(c);
try {
o.notify(); //唤醒
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notify();
}
},"线程1").start();
new Thread(()->{
synchronized (o){
for (char c: chars2){
System.out.println(c);
try {
o.notify(); //唤醒
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notify();
}
},"线程2").start();
}
方法三:ReentrantLock
public static void main(String[] args){
ReentrantLock lock = new ReentrantLock();
Condition condition1 = lock.newCondition(); //分队列
Condition condition2 = lock.newCondition();
CountDownLatch latch = new CountDownLatch(1); //决定哪个线程先执行
char[] chars = "123456".toCharArray();
char[] chars2 = "ABCDEF".toCharArray();
new Thread(()->{
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.lock();
try {
for (char c: chars){
System.out.println(c);
condition2.signal();
condition1.await();
}
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}).start();
new Thread(()->{
lock.lock();
try {
latch.countDown();
for (char c: chars2){
System.out.println(c);
condition1.signal();
condition2.await();
}
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}).start();
}
日志输出
1
A
2
B
3
C
4
D
5
E
6
F