}
package thead;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadWaitAndNotifyTest1 {
/**
* @param args
*/
public static void main(String[] args) {
ExecutorService es = Executors.newCachedThreadPool();
//Resource r = new Resource();
resourceLock r1 = new resourceLock();
es.execute(new Task2(r1));
es.execute(new Task1(r1));
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(es.shutdownNow());
// es.shutdown();
System.out.println("任务圆满结束");
}
}
class Task1 implements Runnable {
private resourceLock r;
public Task1(resourceLock r) {
this.r = r;
}
@Override
public void run() {
while (!Thread.interrupted()) {
r.baoJiaozi();// 执行包饺子
// TimeUnit.MILLISECONDS.sleep(2);
try {
r.waitZhuJiaozi();// 等待煮饺子
} catch (InterruptedException e) {
System.out.println("包饺子任务被关闭了");
break;
}
}
}
}
class Task2 implements Runnable {
private resourceLock r;
public Task2(resourceLock r) {
this.r = r;
}
@Override
public void run() {
try {
while (!Thread.interrupted()) {
r.zhuJiaozi();// 执行煮饺子
// TimeUnit.MILLISECONDS.sleep(2);
r.waitBaoJiaozi();// 等待包饺子
}
} catch (InterruptedException e) {
System.out.println("煮饺子任务被关闭了");
}
}
}
class Resource {
private boolean status = false;// false包饺子可以
public synchronized void baoJiaozi() {
status = true;
System.out.println("包饺子");
notifyAll();
}
public synchronized void zhuJiaozi() {
status = false;
System.out.println("煮饺子");
notifyAll();
}
public synchronized void waitBaoJiaozi() throws InterruptedException {
while (!status) {
wait();
}
}
public synchronized void waitZhuJiaozi() throws InterruptedException {
while (status) {
wait();
}
}
}
class resourceLock {
private boolean status = false;// false包饺子可以
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void baoJiaozi() {
lock.lock();
try {
status = true;
System.out.println("包饺子");
condition.signalAll();
} finally {
lock.unlock();
}
}
public void zhuJiaozi() {
lock.lock();
try {
status = false;
System.out.println("煮饺子");
condition.signalAll();
} finally {
lock.unlock();
}
}
public void waitBaoJiaozi() throws InterruptedException {
lock.lock();
try {
while (!status) {
condition.await();
}
} finally {
lock.unlock();
}
}
public void waitZhuJiaozi() throws InterruptedException {
lock.lock();
try {
while (status) {
condition.await();
}
} finally {
lock.unlock();
}
}
}