Java里有两种多线程的实现方式,一种是继承Thread类,一种是实现Runnable接口,面试时候突然被问到这两种方式有什么区别呢?
我一直习惯性的使用实现Runnable接口的方式来实现多线程,但是它们有什么区别?还真没细想过。。。。于是问了问度受,答案真是("▔□▔) 。。。好吧用的时候知道但是说却一时说不出。。哎语文老师死得太早了
第一种方式,继承Thread类:
public class Test {
public static void main(String args[]) throws IOException, Exception {
ThreadTest t1 = new ThreadTest();
ThreadTest t2 = new ThreadTest();
ThreadTest t3 = new ThreadTest();
t1.start();
t2.start();
t3.start();
}
}
class ThreadTest extends Thread {
private int total = 10;
@Override
public void run() {
// TODO Auto-generated method stub
while(total>0){
total--;
System.out.println("now total value is:" + total);
}
}
}
运行结果:
now total value is:9
now total value is:8
now total value is:7
now total value is:6
now total value is:5
now total value is:4
now total value is:3
now total value is:2
now total value is:1
now total value is:0
now total value is:9
now total value is:8
now total value is:7
now total value is:6
now total value is:9
now total value is:8
now total value is:7
now total value is:6
now total value is:5
now total value is:4
now total value is:3
now total value is:2
now total value is:1
now total value is:0
now total value is:5
now total value is:4
now total value is:3
now total value is:2
now total value is:1
now total value is:0
第二种方式,实现runnable接口:
public class Test {
public static void main(String args[]) throws IOException, Exception {
Runnable r = new RunnableTest();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
Thread t3 = new Thread(r);
t1.start();
t2.start();
t3.start();
}
}
class RunnableTest implements Runnable {
private int total = 10;
@Override
public void run() {
// TODO Auto-generated method stub
while(total>0){
total--;
System.out.println("now total value is:" + total);
}
}
}
运行结果:
now total value is:8
now total value is:8
now total value is:7
now total value is:5
now total value is:6
now total value is:3
now total value is:4
now total value is:1
now total value is:2
now total value is:0
简单来说就是第一种方法是多线程执行多个任务,第二种方法是多线程执行单个任务。第二个方法由于(本人太懒测试程序)没使用同步关键字明显的出现了读写脏数据的现象。事实上我一般想要多线程执行多个任务时也是习惯于用第二种方法只是多实例化几个Runnable实例,于是这问题我死活也答不出来啊= =