《Java基础⼊门第2版》--⿊马程序员课后答案及其详解第10章多线程
⽂章⽬录
⼀、填空题
1、Thread、Runnable、Callable
2、synchronized、this
3、NEW(新建状态)、RUNNABLE(可运⾏状态)、BLOCKED(阻塞状态)、WAITING(等待状态)、TIMED_WAITING(定时等待状态)、TERMINATE D(终⽌状态)
4、开启⼀个新线程、run()⽅法
5、setDaemon(true)、start()
⼆、判断题
1、错
2、对
java入门课件3、对
4、错
5、对
三、选择题
1、AC
2、BC
3、ABC
4、C
5、ABCD
四、简答题
1、⼀种是继承java.lang包下的Thread类,覆写Thread类的run()⽅法,在run()⽅法中实现运⾏在线程上的代码。
new Thread() {
public void run(){}
}.start();
另⼀种就是实现java.lang.Runnable接⼝,同样是在run()⽅法中实现运⾏在线程上的代码。
class MyThread implements Runnable{
public void run(){}
}
另⼀种就是实现urrent.Callable接⼝,同样是在call()⽅法中实现运⾏在线程上的代码。
class MyThread implements Callable{
public Object call() throws Exception{}
}
2、 调⽤sleep(long millis)⽅法,正在执⾏的线程主动让出CPU去执⾏其他线程,在sleep(long millis)⽅法指定的时间过后,CPU才会回到这个线程上继续往下执⾏,如果当前线程进⼊了同步锁,sleep(long millis)⽅法并不会释放锁,即使当前线程使⽤sleep(long millis)⽅法让出了CPU,但其他被同步锁挡住了的线程也⽆法得到执⾏。wait()在⼀个已经进⼊了同步锁的线程内进⾏调⽤,让当前线程暂时让出同步锁,以便其它正在等待此锁的线程可以得到同步锁并运⾏。当其它线程调⽤了notify()或notifyAll()⽅法后,调⽤wait()⽅法的线程就会解除wait状态,当再次获得同步锁后,程序可以继续向下执⾏。
3、 单线程的程序都是从main()⽅法⼊⼝开始执⾏到程序结束,整个过程只能顺序执⾏,如果程序在某个地⽅出现问题,那么整个程序就会崩溃,所以这就说明了单线程在某些⽅⾯的脆弱性和局限性。。
五、编程题
1.public class Test01 {
public static void main(String[] args){
Teacher t =new Teacher();
new Thread(t,"陈⽼师").start();
new Thread(t,"⾼⽼师").start();
new Thread(t,"李⽼师").start();
}
}
class Teacher implements Runnable {
private int notes =80;
public void run(){
while(true){
dispatchNotes();// 调⽤售票⽅法
if(notes <=0){
break;
}
}
}
private synchronized void dispatchNotes(){
if(notes >0){
try{
Thread.sleep(10);// 经过的线程休眠10毫秒
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"---发出的笔记"
+ notes--);
}
}
}
2.public class Accumulator extends Thread {
private int stratNum;
public static int sum;
public Accumulator(int startNum){
this.stratNum = startNum;
}
public static synchronized void add(int num){
sum += num;
}
public void run(){
int sum =0;
for(int i =0; i <10; i++){
sum += stratNum + i;
}
add(sum);
}
public static void main(String[] args)throws Exception {
Thread[] threadList =new Thread[10];
for(int i =0; i <10; i++){
threadList[i]=new Accumulator(10* i +1);
threadList[i].start();
}
Thread.sleep(1000);
System.out.println("Sum is : "+ sum);
}
}
六、原题及其解析
暂⽆。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。