java实验15-多线程2---答案.doc
文本预览下载声明
实验十五 多线程(二)一、实验时间: 姓名: 学号: 实验目的掌握线程之间的通信;理解线程的生命周期;三、知识点1、wait()方法;2、notify()方法;3、notifyAll()方法;4、线程状态转换图;四、实验内容与步骤1、根据线程的生命周期,画出线程的状态转换图。start()start()RunnableRunningBlocked in Object’s lock poolBlocked in Object’s wait poolrun() completesSchedulersynchronized得到锁旗标wait()并释放锁旗标notify()或interrupt()notify()或interrupt()2、编写程序实现以下功能:包括两个进程,分别是生产者进程和消费者进程。生产者进程依次提供:(面条,筷子)或(牛排,叉子),要求生产者每次提供食品和餐具后,要告知消费者取走,而消费者取走食品和餐具后,也要告知生产者已经取走,可以继续提供食品和餐具。public class Q { private String food; private String tool; boolean bFull=false; public synchronized void put(String food,String tool){ if(bFull) try{ wait(); } catch(Exception e){ System.out.println(e.getMessage()); } this.food=food; this.tool=tool; bFull=true; notify(); } public synchronized void get(){ if(!bFull){ try{ wait(); } catch(Exception e){ System.out.println(e.getMessage()); } } System.out.println(food+----+tool); bFull=false; notify(); }}生产者:public class Producer implements Runnable{ Q q; public Producer(Q q){ this.q=q; } public void run(){ int i=0; while(true){ if(i==0) q.put(面条, 筷子); else q.put(牛排, 叉子); i=(i+1)%2; } }}消费者:public class Consumer implements Runnable { Q q; public Consumer(Q q){ this.q=q; } public void run() { while(true){ q.get(); } }}测试类:public class TestQ { public static void main(String[] args) { Q q=new Q(); new Thread(new Producer(q)).start(); new Thread(new Consumer(q)).start(); }}3、编写程序实现以下功能:包括一个生产车票的进程和四个售票的进程。生产进程每次提供100张车票,四个售票进程来卖票。当无票可售时,售票进程要等待。当有票时,生产进程要通知售票进行来售票。//TicketsGame.javapublic class TicketsGame { private int tickets; public synchronized void sale(){ try { Thread.sleep(500); } catch(Exception e){ System.out.println(e.getMessage()); } if(tickets=0){ try { System.out.println(Thread.currentThread().getName()+---等待); wait(); } catch(Exception e){ e.getMessage(); } } else{ System.out.println(Thread.currentThread().getName()+ ---出售第+tickets--+张票!); } }
显示全部