当前位置:首页 > Java第6~18章例题分析与书后答案
}
}
System.out.println(\
//引发异常
} else { int result = 2 / 0;
}
} catch (Exception e) { }
System.out.println(\flag=!flag; } finally {
}
例9.1.5设计两个线程,一个每隔1秒钟显示一次系统时间,另一个每隔5秒显示一次系统时间,对比两个线程的输出结果。 【分析】编写Thread类的子类,重写run()方法,利用SimpleDateFormat类格式化时间,用关键字synchronized实现线程的同步。 参考代码:
import java.text.SimpleDateFormat; import java.util.Date; public class ShowTime { }
class MyShow extends Thread{ private int internal;
public MyShow(int i){ this.internal=i; }
public synchronized void run() { while(true){
try { SimpleDateFormat sdf=new SimpleDateFormat(\
Date dt=new Date();
System.out.println(this.getName()+\当前时间--\
public static void main(String[] args) { MyShow s1=new MyShow(1); }
MyShow s5=new MyShow(5); s1.start();s5.start();
sleep(internal*1000);
} catch (InterruptedException e) {
}
}
e.printStackTrace();
} }
9.2习题解答
1.什么是线程?什么是进程?它们有什么区别? 参考答案:
进程是程序的一次执行,对应了从代码的加载、执行到执行结束的完整过程。 线程是比进程更小的执行单元,是程序执行流的最小单元。
它们的区别主要是:每个进程对应一个单独的地址空间,而多个线程共用一个存储空间;一个进程可以产生若干个线程,进程负责线程的创建和启动。
2.如何创建一个线程,实现Runnable接口和继承Thread类有什么区别? 参考答案:
线程的创建有两种方法:一种是通过实现Runnable接口;另一种通过继承Thread类实现。实现Runnable接口时,在run()方法中实现规定的功能;继承Thread类时,通过重写该类的run()方法实现规定的功能。
3.什么是线程的同步,为什么要实现线程的同步? 参考答案:
线程同步是指多个线程有序访问某个/些资源的机制。当多个线程同时访问一个对象时,为了保持对象数据的统一性和完整性,必须采用线程的同步机制。 4.run()方法在()方法被调用后执行。 A.init() C.start() 答案:C
5.分析下面的代码,选择所有正确的选项。
public class Test {
public static void main(String[] args) {
Thread t=new Thread(); t.start();
B.begin() D.create()
} }
A.Test类必须继承Thread类
B.Test类必须实现Runnable接口
C.由于未实现run()方法,因此会出现运行时错误 D.这段代码没有任何错误
答案:D
6.编写一个程序,用于实现Runnable接口并创建两个线程,分别输出从10到15的数,每个数字间延迟500毫秒,要求输出的结果如下所示:
10,11,12,13,14,15 10,11,12,13,14,15 提示:采用线程同步的方法。 参考代码: class Sync{
public static synchronized void print(){ try { } }
public class Ex06 implements Runnable {
public static void main(String[] args) { Thread t1=new Thread(new Ex06());
Thread t2=new Thread(new Ex06()); t1.start(); t2.start();
}
for(int i=10;i<=15;i++){ }
System.out.println(); e.printStackTrace();
System.out.print(i); if(i!=15) System.out.print(\Thread.sleep(500);
} catch (InterruptedException e) {
}
public void run() { }
}
7.编写一个采用多线程技术的程序,对10000个数据求累加和? 参考代码:
public class Ex07 extends Thread{
private int start;
private int len;
private static double[] arr;
Sync.print();
public static double sum; public Ex07(int start,int len){ this.start=start;
this.len=len;
arr=new double[10000]; for(int i=0;i<10000;i++){ }
arr[i]=Math.random();
}
public static void main(String[] args) { }
@Override
public void run() { }
}
8.编写一个程序,创建3个线程,分别输出26个字母。在输出结果时要指明是哪个线程输出的字母。 参考代码:
class Syn extends Thread{
private char ch='a';
public Syn(String name){
setName(name); }
public void run() { }
char temp;
for(int i=0;i<26;i++){ }
temp=(char)(ch+i);
System.out.println(this.getName()+\for(int i=start;i t1.start();t2.start();t3.start();t4.start();t5.start(); System.out.println(\
共分享92篇相关文档