Java中 Thread和Runnable实现多线程的区别和联系

时间:2022-12-28 17:34:22

Java有两种方式实现多线程,第一个是继承Thread类,第二个是实现Runnable接口。他们之间的联系:

1、Thread类实现了Runable接口。

2、都需要重写里面Run方法。

他们之间的区别“

1、实现Runnable的类更具有健壮性,避免了单继承的局限。

2、Runnable更容易实现资源共享,能多个线程同时处理一个资源。

看一下以继承Thread的卖票例子:

public static void main(String[] args) {
// TODO Auto-generated method stub

new MyThread().start();
new MyThread().start();

}


class MyThread extends Thread{
private int ticket = 5;
public void run(){
while(true){
System.out.println("Thread ticket = " + ticket--);
if(ticket < 0){
break;
}
}
}
}
输出结果:
Thread ticket = 5Thread ticket = 5Thread ticket = 4Thread ticket = 4Thread ticket = 3Thread ticket = 2Thread ticket = 3Thread ticket = 1Thread ticket = 2Thread ticket = 0Thread ticket = 1Thread ticket = 0

从以上输出结果可以看出,我们创造了2个多线程对象,他们分别实现了买票任务,也就是一共卖了12张票。

 
实现Runnable接口的卖票例子:
<pre name="code" class="html">public static void main(String[] args) {		// TODO Auto-generated method stub		MyThread2 m=new MyThread2();			new Thread(m).start();			new Thread(m).start();						}class MyThread2 implements Runnable{      private int ticket = 5;      public void run(){      	 while(true){    		 System.out.println("Runnable ticket = " + ticket--);               if(ticket < 0){                  break;             }           }     }  }  
输出结果:
 
Runnable ticket = 5
Runnable ticket = 4
Runnable ticket = 3
Runnable ticket = 2
Runnable ticket = 1
Runnable ticket = 0


从结果我们可以看到,虽然我们声明了两个线程,但是一共卖了6张票。他们实现了资源共享。PS:在实际开发中,一定要注意命名规范,其次上面实现Runable接口的例子由于同时操作一个资源,会出现线程不安全的情况,如果情况需要,我们需要进行同步操作。