《Java基础入门第2版》--黑马程序员 课后答案及其详解 第10章 多线程

一、填空题

1、Thread、Runnable、Callable
2、synchronized、this
3、NEW(新建状态)、RUNNABLE(可运行状态)、BLOCKED(阻塞状态)、WAITING(等待状态)、TIMED_WAITING(定时等待状态)、TERMINATED(终止状态)
4、开启一个新线程、run()方法
5、setDaemon(true)、start()

二、判断题

1、错   2、对   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(){}
}
另一种就是实现java.util.concurrent.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);
	}
}

六、原题及其解析

暂无。

  • 19
    点赞
  • 120
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

香鱼嫩虾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值