LockSupport
LockSupport是一个线程工具类,所有的方法都是静态方法,可以让线程在任意位置阻塞,也可以在任意位置唤醒。它的内部其实两类主要的方法:park(停车阻塞线程)和unpark(启动唤醒线程)。
public class Test{
static Thread t1 = null , t2 = null;
public static void main(){
char[] aI = "1234567".toCharArray();
char[] aC = "ABCDEFG".toCharArray();
t1 = new Thread(()->{
for(char c:aI){
System.out.print(c);
LockSupport.unpark(t2); //唤醒t2
LockSupport.park(); //阻塞
}
},"t1").start();
t2 = new Thread(()->{
for(char c : aC){
LockSupport.park();
System.out.print(c);
LockSupport.unpark(t1);
}
},"t2").start();
}
}
wait() & notify()
利用synchronized 锁定
public class Test{
final Object o = new Object();
public static void main(){
char[] aI = "1234567".toCharArray();
char[] aC = "ABCDEFG".toCharArray();
t1 = new Thread(()->{
sychronized(o){
for(char c : aI) {
System.out.print(c);
try {
o.notify();
o.wait(); //让出锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notify(); //必须,否则无法停止程序
}
},"t1").start();
new Thread(()->{
synchronized (o) {
for(char c : aC) {
System.out.print(c);
try {
o.notify();
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notify();
}
}, "t2").start();
}
}
网友评论