class MyThread extends Thread{
public void run(){
System.out.println("MyThread: run()");
}
public void start(){
System.out.println("MyThread: start()");
}
}
class MyRunnable implements Runnable{
public void run(){
System.out.println("MyRunnable: run()");
}
public void start(){
System.out.println("MyRunnable: start()");
}
}
public class MyTest {
public static void main(String args[]){
MyThread myThread = new MyThread();
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
myThread.start();
thread.start();
}
}
为什么结果是
MyThread: start()
MyRunnable: run()????
Which of the following collection classes from java.util package are Thread safe?
A.Vector
B.ArrayList //与Vector类似,只是不同步
C.HashMap
D.Hashtable
为什么选A.D?
Vector和Hashtable的许多方法都是同步的。故而线程安全!看他们的源码
因为Thread thread = new Thread(myRunnable);//实现了接口
所以
thread.start();时执行的是
public void run(){
System.out.println("MyRunnable: run()");
}方法
另一个没有,只是调用了start()方法而已
1)Thread thread = new Thread(myRunnable);相当于运行MyRunnable这个线程。
2)建议你看一看源代码,看了Vector,ArrayList,HashMap,Hashtable的具体实现你就明白了。