📝个人主页:五敷有你
🔥系列专栏:并发编程
⛺️稳重求进,晒太阳
必须先2后1打印
用synchronized
package aaa;
public class Test2 {
static Boolean hasExecutor=false;
public static void main(String[] args) {
Object obj=new Object();
new Thread(()->{
synchronized (obj){
while (!hasExecutor){
try {
obj.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println(1);
}
}).start();
new Thread(()->{
synchronized (obj){
System.out.println(2);
hasExecutor=true;
obj.notifyAll();
}
}).start();
}
}
用ReentrantLock
static Boolean hasExecutor=false;
public static void main(String[] args) {
ReentrantLock lock=new ReentrantLock();
Condition condition = lock.newCondition();
new Thread(()->{
lock.lock();
try {
while (!hasExecutor){
condition.await();
}
System.out.println(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}).start();
new Thread(()->{
lock.lock();
try {
System.out.println(2);
hasExecutor=true;
condition.signalAll();
}finally {
lock.unlock();
}
}).start();
}
park && unpark
static Boolean hasExecutor=false;
public static void main(String[] args) {
Object obj=new Object();
Thread t1= new Thread(()->{
while (!hasExecutor){
LockSupport.park();
}
System.out.println(1);
});
t1.start();
new Thread(()->{
synchronized (obj){
System.out.println(2);
hasExecutor=true;
LockSupport.unpark(t1);
}
}).start();
}
交替输出abc
用synchronized
package aaa;
public class Test2 {
static Boolean hasExecutor = false;
public static void main(String[] args) {
WaitNotify waitNotify=new WaitNotify(1);
new Thread(()->{
waitNotify.print("a",1,2);
}).start();
new Thread(()->{
waitNotify.print("b",2,3);
}).start();
new Thread(()->{
waitNotify.print("c",3,1);
}).start();
}
}
class WaitNotify {
private Integer flag;
public String str="a";
public Integer waitFlag;
public Integer nextFlag;
public WaitNotify(Integer flag) {
this.flag=flag;
}
void print(String str, Integer waitFlag, Integer nextFlag) {
while (true) {
synchronized (this) {
while (waitFlag != flag) {
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.print(str);
flag=nextFlag;
this.notifyAll();
}
}
}
}
用reentrantLock()实现
- lock.lock()对应synchronized
- condition.await对应wait()
- condition.signalAll 对应 notifyAll
void printLock(String str, Integer waitFlag, Integer nextFlag) {
while (true) {
reentrantLock.lock();
try {
while (waitFlag != flag) {
try {
condition.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.print(str);
flag=nextFlag;
condition.signalAll();
}finally {
reentrantLock.unlock();
}
}
}
用park&unpark
park不需要while()来判断是否虚假唤醒,因为它指定某个线程唤醒
void printPark(String str,Thread t){
while (true) {
LockSupport.park();
System.out.print(str);
flag = nextFlag;
LockSupport.unpark(t);
}
}
结合 线程状态思考