package com.phone.week5.day3;
/*
*练习,有一个篮子,里面可以装馒头,一共可以装6个馒头,
*有一群新东方出来的大师父往里面扔馒头
*有一群千锋出来的IT人员从篮子里拿馒头吃
*1.找出共享的资源
*2.创建生产者
*3.创建消费者
*4.测试
*分析类,属性,方法
*会有一个篮子类,篮子里可以装6个馒头,所以会有一个数组,可以给每个馒头加个标号
*
*/
public class TestManTou {
public static void main(String[] args) {
Basket bas = new Basket();
new Teacher(bas).start();
new Student(bas).start();
}
}
// 生产者
class Teacher extends Thread {
private Basket basket;
public Teacher(Basket basket) {
super();
this.basket = basket;
}
@Override
public void run() {
for (int i = 1; i <= 20; i++) {
try {
Thread.sleep((int) (Math.random() * 3000));
} catch (InterruptedException e) {
e.printStackTrace();
}
Bread b = new Bread(i);
basket.proBread(b); // 生产馒头
}
}
}
// 消费者
class Student extends Thread {
private Basket basket;
public Student(Basket basket) {
super();
this.basket = basket;
}
public void run() {
for (int i = 1; i <= 20; i++) {
try {
Thread.sleep((int) (Math.random() * 3000));
} catch (InterruptedException e) {
e.printStackTrace();
}
Bread b = basket.getBread(); // 消费馒头
}
}
}
// 篮子类
class Basket {
Bread[] br = new Bread[6]; // 可以装6个馒头
int index = 0; // 可以通过索引拿馒头
// 拿馒头的方法,一次只能有一个人拿
public synchronized Bread getBread() {
index--;
if (index <0) {
System.out.println("馒头没有了,请大师父做馒头");
try {
this.notify(); // 叫醒某一个线程
this.wait(); // 自己等
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//System.out.println(Thread.currentThread().getName() + "拿了一个馒头");
System.out.println("拿馒头的索引是:" + index);
return br[index]; // 拿到馒头
}
// 生产馒头,一次只能放一个
public synchronized void proBread(Bread bre) {
if (index == br.length - 1) {
System.out.println("馒头满了,请学生吃馒头");
this.notify(); //叫醒
try {
this.wait(); //等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index++;
//System.out.println("生产了馒头:" + bre.getId());
System.out.println("生产馒头的索引是:" + index);
br[index] = bre;
}
}
// 馒头类
class Bread {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Bread(int id) {
super();
this.id = id;
}
}
package com.phone.week5.day3;
public class TestComm implements Runnable{
public static void main(String[] args) {
TestComm tc = new TestComm();
new Thread(tc,"a").start();
new Thread(tc,"b").start();
}
Object ob = new Object();
@Override
public synchronized void run() {
synchronized (ob) {
for (int i = 0; i <5; i++) {
if(i==2){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
for (int i = 0; i <10; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
if(i==4){
try {
this.wait();//进行等待的状态
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(i==1){
this.notify(); //叫醒正在等待的线程
}
if(i==6){
this.notify();
}
}
}
}