了,于是自己也愉快的结束运行。关键代码见下:
(4)测试类一如既往与书本一样,如下:
该题代码如下:
package zi;
publicclass Ex8_3 {
Thread A = new Thread(\) { };
Thread B = new Thread(\) { };
Thread C = new Thread(\) {
publicvoid run() {
while (true) {
if (!A.isAlive() && !B.isAlive())
return; try {
publicvoid run() { }
Wait(\); publicvoid run() { }
Wait(\);
}
};
}
}
}
Thread.sleep(2000); e.printStackTrace();
} catch (InterruptedException e) {
notifyall();
publicsynchronizedvoid Wait(String name) { }
publicsynchronizedvoid notifyall() { }
publicstaticvoid main(String args[]) { }
Ex8_3 test = new Ex8_3();
//A、B两线程一起输入start和输出end,不过中间有C让线程休眠2秒,没法全部一次//之后再唤醒,让AB继续输出下半部分end test.A.start(); test.B.start(); test.C.start(); notifyAll();
System.out.println(name + \); try { }
System.out.println(name + \);
wait();
e.printStackTrace();
} catch (InterruptedException e) {
性输出,
其运行结果截图如下:
4,课本270页课后习题第5题,记得要实现线程互斥(同步)。
这个跟书本例题差不多的设计方式,记得是生产者与消费者模型,书本展示了两种实现
方式,建议采用第二种比较规范(256页例8-9),这里纯模仿就可以,具体不细说了,大家看说,纯模仿,看结果。
依题意,该题代码如下:
package zi;
import java.util.Scanner; class Data{
String studentId; String name;
booleanavailable = false;// 判断是读是写
Scanner in = new Scanner(System.in);// 定义一个输入对象 publicsynchronizedvoid read() {
if(available)
try { }
catch(Exception e) { }
wait();
System.out.printf(\请输入学号:\); try { }
catch(Exception e) { }
System.out.printf(\请输入姓名:\);
System.out.println(\输入学号出错!\); studentId=in.next();
}
}
try { }
catch(Exception e) { }
System.out.println(); available=true; notify();
System.out.println(\输入姓名出错!\); name=in.next();
publicsynchronizedvoid write() { }
if(!available)
try { }
catch(Exception e) { }
wait();
System.out.println(\输出学生学号:\+studentId+\姓名:\+name+\); available=false; notify();
//Read类
class Read extends Thread{ }
Data d1 = null; public Read(Data d){ }
publicvoid run(){ }
while(true) { }
d1.read(); this.d1=d;
//Write类
class Write extends Thread{ }
publicclass Ex8_4 { }
publicstaticvoid main(String[] args){ }
Data data=new Data(); new Read(data).start(); new Write(data).start();
Data d2=null; public Write(Data d) { }
publicvoid run() { }
while(true) { }
d2.write(); this.d2=d;
执行结果截图如下:
5,课本270页课后习题第10题。这一题主要运用wait()和notify()来同步,这个程序本身是一个进程,里面根据题意一共设计只有两个线程,一个wait,然后notify自然
百度搜索“77cn”或“免费范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,免费范文网,提供经典小说教育文库java 实验八 多线程 实验报告(2)在线全文阅读。
相关推荐: