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() {
synchronized(System.out) {
for (int i = 0; i < 100; i++) {
System.out.println(data);
}
}
}
}
C 因为t1、t2线程分别对应的是两个不同的资源对象,所以AB错误
9.(线程综合)代码改错
public class TestMyThread {
public static void main(String[] args) {
Runnable t1 = new MyThread1();
Thread t11 = new Thread(t1);
Thread t2 = new MyThread2();
t11.start();
t2.start();
}
}
class MyThread1 implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
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 {
public void run() {
for (int i = 0; i < 100; i++) {
try {
this.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("world");
}
}
}