继承Thread和实现Runable都可以实现多线程,下面通过一个实例说明两者的区别:
1、继承Thread类多线程(Thread实质也是Runnable的接口的子类)
public class MyThread1 extends Thread{
private int ticket=10;
public void run(){
for(int i=0;i<20;i++){
if(this.ticket>0){
System.out.println("卖票:ticket"+this.ticket--);
}
}
}
public static void main(String[] args) {
MyThread1 mt1=new MyThread1();
MyThread1 mt2=new MyThread1();
MyThread1 mt3=new MyThread1();
mt1.start();//每个线程都各卖了10张,共卖了30张票
mt2.start();//但实际只有10张票,每个线程都卖自己的票
mt3.start();//没有达到资源共享 }
}
}
输出:
卖票:ticket10
卖票:ticket9
卖票:ticket8
卖票:ticket7
卖票:ticket6
卖票:ticket5
卖票:ticket4
卖票:ticket3
卖票:ticket2
卖票:ticket1
卖票:ticket10
卖票:ticket9
卖票:ticket8
卖票:ticket7
卖票:ticket6
卖票:ticket5
卖票:ticket4
卖票:ticket3
卖票:ticket2
卖票:ticket1
卖票:ticket10
卖票:ticket9
卖票:ticket8
卖票:ticket7
卖票:ticket6
卖票:ticket5
卖票:ticket4
卖票:ticket3
卖票:ticket2
卖票:ticket1
2、实现Runnable接口
public class TestRunable implements Runnable{
private int ticket=10;
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<20;i++){
if(this.ticket>0){
System.out.println("卖票:ticket"+this.ticket--);
}
}
}
public static void main(String[] args) {
TestRunable mt=new TestRunable();
new Thread(mt).start();//同一个mt,但是在Thread中就不可以,如果用同一
new Thread(mt).start();//个实例化对象mt,就会出现异常
new Thread(mt).start(); }
}
输出:
卖票:ticket10
卖票:ticket9
卖票:ticket8
卖票:ticket7
卖票:ticket5
卖票:ticket3
卖票:ticket2
卖票:ticket1
卖票:ticket6
卖票:ticket4
总结一下两者的区别:
·一个类可以实现多个接口,但只能继承一个类
·Runnable可以实现资源共享
补充,另附一道SCJP的考试题:
public class MyThread implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("run");
throw new RuntimeException("Problem");
}
public static void main(String[] args) {
Thread thread = new Thread(new MyThread());
thread.start();
System.out.println("End of method");
}
}
Which two can be results? (Choose two.)
A. java.lang.RuntimeException: Problem
B. run
java.lang.RuntimeException: Problem
C. End of method.
java.lang.RuntimeException: Problem
D. End of method.
run.
java.lang.RuntimeException: Problem
E. run
java.lang.RuntimeException: Problem
End of method