Java语言程序设计 第八章课后习题答案
1.进程和线程有何区别,Java是如何实现多线程的。 答:区别:一个程序至少有一个进程,一个进程至少有一个线程;线程的划分尺度小于进程;进程在执行过程中拥有独立的内存单元,而多个线程共享内存,从而极大地提高了程序的运行效率。
Java程序一般是 继承Thread 类 或者实现 Runnable接口,从而实现多线程。
2.简述线程的生命周期,重点注意线程阻塞的几种情况,以及如何重回就绪状态。 答:线程的声明周期:新建-就绪-(阻塞)-运行--死亡
线程阻塞的情况:休眠、进入对象wait池等待、进入对象lock池等待;
休眠时间到回到就绪状态;在wait池中获得notify()进入lock池,然后获得锁棋标进入就绪状态。
3.随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000毫秒以内),哪个先显示完毕,就决定去哪个城市。分别用Runnable接口和Thread类实现。
(注:两个类,相同一个测试类) //Runnable接口实现的线程runable类
public class runnable implements Runnable { private String city; public runnable() {}
public runnable(String city) { this.city = city; }
public void run() {
for (int i = 0; i < 10; i++) { System.out.println(city); try {
//休眠1000毫秒。
Thread.sleep(1000);
} catch (InterruptedException e) { e.printStackTrace(); } } } }
// Thread类实现的线程thread类
public class runnable extends Thread { private String city; public runnable() {}
public runnable(String city) { this.city = city; }
public void run() {
for (int i = 0; i < 10; i++) { System.out.println(city); try {
//休眠1000毫秒。
Thread.sleep(1000);
} catch (InterruptedException e) { e.printStackTrace(); } } } }
//test8_3
public class test8_3 { }
public static void main(String[] args) { }
// 将创建一个线程对象,这个对象接受一个实现了Runnable接口。实际上这里也就runnable r1=new runnable(\广州\); runnable r2=new runnable(\乌鲁木齐\); Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); // 启动线程 t1.start(); t2.start();
是使用run()方法
运行结果分别为:
4.编写一个多线程程序实现如下功能:线程A和线程B分别在屏幕上显示信息“…start”后,调用wait等待;线程C开始后调用sleep休眠一段时间,然后调用notifyall,使线程A和线程B继续运行。线程A和线程B恢复运行后输出信息“…end”后结束,线程C在判断线程B和线程A结束后自己结束运行。
//test8_4
public class test8_4 {
Thread A = new Thread(\) { };
Thread B = new Thread(\) { };
Thread C = new Thread(\) {
public void run() {
while (true) {
if (!A.isAlive() && !B.isAlive())
return;
public void run() { }
Wait(\); public void run() { }
Wait(\);
}
};
}
}
try { }
notifyall();
Thread.sleep(2000); e.printStackTrace();
} catch (InterruptedException e) {
public synchronized void Wait(String name) { }
public synchronized void notifyall() { }
public static void main(String args[]) { }
test8_4 test = new test8_4();
//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) {
次性输出,
运行结果:
5.实现一个数据单元,包括学号和姓名两部分。编写两个线程,一个线程往数据单元中写,另一个线程往外读。要求没写一次就往外读一次。 //Data类
import java.util.Scanner; public class Data{
String studentId; String name;
boolean available = false;// 判断是读是写
Scanner in = new Scanner(System.in);// 定义一个输入对象 public synchronized void read() {
if(available)
try { }
catch(Exception e) { }
wait();
System.out.printf(\请输入学号:\); try { }
catch(Exception e) {
System.out.println(\输入学号出错!\); }
System.out.printf(\请输入姓名:\); try { }
catch(Exception e) {
System.out.println(\输入姓名出错!\); }
System.out.println(); available=true; notify();
name=in.next(); studentId=in.next();
(完整word版)Java语言程序设计(郑莉)第八章课后习题答案



