关键字 wait(); notify()
// 创建 tong mantou chushi xiaofeizhe 四个类。
mantou具有ID
tong 具有容量 mantou[]数组,及 index 馒头的数量
chushi生产mantou
xiaofeizhe 消费mantou
public class Test20180601{
public static void main(String args[]){tong t1 = new tong();
chushi c1 = new chushi(t1);
xiaofeizhe x1 = new xiaofeizhe(t1);
new Thread(c1).start();
new Thread(x1).start();
}
}
class mantou {
int ID=0;
mantou(int i){
ID = i;
}
public String toString(){
return ""+ID;
}
}
class tong{
int index = 0;
mantou[] arrTong = new mantou[6];
public synchronized void push(mantou mt){
if (index == arrTong.length){ //判断当tong内的index 馒头数量等于 arrTong 桶的容 量时, this.wait() 停止当前对象上的线程(生产者)。
try{
this.wait();
}catch (Exception e){
}
}
this.notify();
arrTong[index] = mt;
index ++;
}
public synchronized mantou pop(){
if (index == 0){ //判断当tong内的index 馒头数量等于 0时 即桶内没有馒 头时, this.wait() 停止当前对象上的线程(消费者)。
try{
this.wait();
}catch (Exception e){
}
}
this.notify();
index --;
return arrTong[index];
}
}
class chushi implements Runnable {
tong s1 = null;
chushi(tong s1){
this.s1 = s1;
}
public void run(){
for (int i =0;i <=20 ;i++ ){
mantou mt = new mantou(i);
s1.push(mt);
System.out.println("生产者生产了馒头:" + mt);
try{
Thread.sleep(1000);
}catch (InterruptedException e){
}
}
}
}
class xiaofeizhe implements Runnable{
tong s2 = null;
xiaofeizhe(tong s2){
this.s2 = s2;
}
public void run(){
for (int i = 0;i <=20 ;i++ ){
mantou mt = s2.pop();
System.out.println("消费者消费了馒头:" + mt);
try{
Thread.sleep(1000);
}catch (InterruptedException e){
}
}
}
}
总结
Wait Objcet的方法
Sleep Thread的方法
Wait 停止线程时放开锁
Sleep 睡眠时不放开锁
线程:一个程序里不同的执行路径
进程:一个class文件 一个exe文件 静态的概念
创建和启动线程的两种方式:从Thread类继承 重写run方法 实现接口
sleep:睡眠
join:
yield:
synchronized:锁定某个对象
wait:睡眠
notify:叫醒wait在某一个对象上的其他线程
notifyAll:叫醒wait在某一个对象上的所有线程