在千锋逆战学习Java的第29天
今天学习了多线程的同步规则、等待(wait)与通知(notify)、线程池的概念和原理、Callable接口和Future接口。
作业题:
8.有以下代码
public class TestMyThread {
public static void main(String[] args) {
Thread t1 = new MyThread("aaa");
Thread t2 = new MyThread("bbb");
t1.start();
t2.start();
}
}
class MyThread extends Thread {
private String data;
public MyThread(String data) {
this.data = data;
}
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(data);
}
}
}
答:C,out是System类里的一个属性,对out这个属性加锁,t1、t2用的System.out是同一个
9.代码改错
public class TestMyThread {
public static void main(String[] args) {
Runnable t1 = new MyThread1();
Thread t2 = new MyThread2();
t1.start();
t2.start();
}
}
class MyThread1 implements Runnable{
public void run(){
for(int i =0; i<100;i++){
this.sleep((int)(Math.random()*1000));
System.out.println("hello");
}
}
}
class MyThread2 extends Thread{
public void run() throws Exception{
for(int i= 0; i<100; i++){
this.sleep((int)(Math.random()*1000));
System.out.println("world");
}
}
}
修改后代码如下:
public class TestMyThread {
public static void main(String[] args) {
Runnable t1 = new MyThread1();
Thread t2 = new MyThread2();
// 错误。t1不是线程,是一个任务类对象,要传入一个线程对象
Thread t3 = new Thread(t1);
t3.start();
t2.start();
}
}
class MyThread1 implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
//错误。MyThread1没有sleep方法,要用Thread直接调用sleep方法,并用tryCatch处理异常
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("hello");
}
}
}
class MyThread2 extends Thread {
// 错误。run方法不能声明异常
public void run() {
for (int i = 0; i < 100; i++) {
// 错误。用tryCatch语句处理this.sleep()异常
try {
this.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("world");
}
}
}