java 实验八 多线程 实验报告(2)

2020-03-27 19:51

了,于是自己也愉快的结束运行。关键代码见下:

(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自然


java 实验八 多线程 实验报告(2).doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:减免税管理办法

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: