package com.mage.thread;publicclassTest01{//main方法中的线程称之为主线程publicstaticvoidmain(String[] args){//创建子类对象
Sun s =newSun();
s.start();//main方法执行输出for(int i =0;i<10;i++){
System.out.println("线程main执行》》》》"+i);}}}classSunextendsThread{publicvoidrun(){for(int i =0;i<10;i++){
System.out.println("线程Sun执行》》》》"+i);}}}
package com.mage.thread.part;import java.io.ObjectInputStream.GetField;import java.util.concurrent.TimeUnit;publicclassGood{private String type;private String name;// 代表有无商品privateboolean flag =false;publicGood(){// TODO Auto-generated constructor stub}publicGood(String type,String name){super();this.type = type;this.name = name;}public String getType(){return type;}publicvoidsetType(String type){this.type = type;}public String getName(){return name;}publicvoidsetName(String name){this.name = name;}//生产对象publicsynchronizedvoidproduct(int i){if(flag){try{wait();}catch(InterruptedException e){// TODO Auto-generated catch block
e.printStackTrace();}}if(i%2==0){this.setType("可口可乐");try{
TimeUnit.MILLISECONDS.sleep(100);}catch(InterruptedException e){// TODO Auto-generated catch block
e.printStackTrace();}this.setName("可乐");}else{this.setType("SkII");try{
TimeUnit.MILLISECONDS.sleep(100);}catch(InterruptedException e){// TODO Auto-generated catch block
e.printStackTrace();}this.setName("神仙水");}
System.out.println("开始生产:商品"+this);//改变flag的值
flag =true;//叫醒等待的线程notifyAll();}//消费publicsynchronizedvoidconsumer(){if(!flag){try{wait();}catch(InterruptedException e){// TODO Auto-generated catch block
e.printStackTrace();}}
System.out.println("开始消费:商品"+this);
flag =false;notifyAll();}@Overridepublic String toString(){return"[type="+type+"\tname="+name+"]";}}
package com.mage.thread.part;publicclassProductextendsThread{private Good good;publicProduct(Good good){this.good = good;}@Overridepublicvoidrun(){for(int i =1;i<10;i++){
good.product(i);}}}
package com.mage.thread.part;publicclassConsumerextendsThread{private Good good;publicConsumer(Good good){this.good = good;}@Overridepublicvoidrun(){for(int i=1;i<10;i++){
good.consumer();}}}
package com.mage.thread.part;publicclassGoodTest{publicstaticvoidmain(String[] args){
Good g =newGood();
Product p =newProduct(g);
Consumer c =newConsumer(g);
p.start();
c.start();}}