Java.util.concurrent.locks.LockSupport.java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.LockSupport;
public class ProviderConsumer {
private static int bean;
public static void main(String[] args) throws Exception {
ProviderConsumer ps = new ProviderConsumer();
ps.park_unpark();
}
private void park_unpark() throws Exception {
Thread c, p;
//内部类要求被引用的外部变量必须为final,本例还要求这个被引用变量后续可以更新内部属性,那么这个变量应该指向一个对象。这里为了方便就都放集合里了
final List<Thread> fp = new ArrayList<>();
final List<Thread> fc = new ArrayList<>();
Random random = new Random();
c = new Thread(() -> {
while (true) {
try {
int r = random.nextInt(3000);
System.out.println("==================================================="+r);
Thread.sleep(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (bean == 0) {
if (fp != null || fp.size() > 0) {
System.out.println("给生产者颁发许可" + bean);
//正是这里在引用外部变量
LockSupport.unpark(fp.get(0));
}
System.out.println("consumer挂起");
LockSupport.park();
}
System.out.println("消费前"+bean);
bean--;
System.out.println("消费后"+bean);
}
});
p = new Thread(() -> {
while (true) {
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (bean == 1) {
if (fc != null || fc.size() > 0) {
System.out.println("给消费者颁发许可" + bean);
//还有这里在引用外部变量
LockSupport.unpark(fc.get(0));
}
System.out.println("provider挂起");
LockSupport.park();
}
System.out.println("生产前"+bean);
bean++;
System.out.println("生产后"+bean);
}
});
fp.add(p);
fc.add(c);
p.start();
c.start();
}
}