一、填空题
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();
}
System.out.println("Sum is : " + sum);
}
}
六、原题及其解析
暂无。