java实验15 多线程2 - 答案
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
实验十五多线程(二)
一、实验时间:姓名:学号:
二、实验目的
1、掌握线程之间的通信;
2、理解线程的生命周期;
三、知识点
1、wait()方法;
2、notify()方法;
3、notifyAll()方法;
4、线程状态转换图;
四、实验内容与步骤
1、根据线程的生命周期,画出线程的状态转换图。
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.java
public 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--+"张票!");
}
}
public synchronized void produce(){
try
{
Thread.sleep(50);
}
catch(Exception e){
System.out.println(e.getMessage());
}
tickets=tickets+3;
System.out.println("现在有"+tickets+"张票!");
notifyAll();
}
}
//售票
public class Consumer implements Runnable{ private TicketsGame q;
public Consumer(TicketsGame q){
this.q=q;
}
public void run(){
while(true)
q.sale();
}
}
//生产票
public class Producer implements Runnable{ private TicketsGame q;
public Producer(TicketsGame q){
this.q=q;
}
public void run(){
while(true)
q.produce();
}
}
//测试类
public class TestTickets {
public static void main(String[] args) {
TicketsGame q=new TicketsGame();
Thread c1=new Thread(new Consumer(q));
c1.setName("北京西站");
Thread c2=new Thread(new Consumer(q));
c2.setName("北京东站");
Thread c3=new Thread(new Consumer(q));