首页 > 代码库 > java中利用继承类和Runnable接口实现多线程的区别
java中利用继承类和Runnable接口实现多线程的区别
利用继承Thread类实现的多线程无法资源共享
如下程序
class MyThread extends Thread{
public MyThread(String name){
super();
this.name=name;
}
public void run(){
while(tickets==0?false:true)
{
tickets--;
System.out.println(name+" just selt one ticket,only "+tickets+" left");
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private int tickets=10;
private String name;
}
public class SellTickets{
public static void main(String[] args){
MyThread aMyThread1=new MyThread("MyThread 1");
MyThread aMyThread2=new MyThread("MyThread num 2");
aMyThread1.start();
aMyThread2.start();
}
}
打印结果如下:
MyThread 1 just selt one ticket,only 9 left
MyThread num 2 just selt one ticket,only 9 left
MyThread 1 just selt one ticket,only 8 left
MyThread num 2 just selt one ticket,only 8 left
MyThread num 2 just selt one ticket,only 7 left
MyThread 1 just selt one ticket,only 7 left
MyThread num 2 just selt one ticket,only 6 left
MyThread 1 just selt one ticket,only 6 left
MyThread num 2 just selt one ticket,only 5 left
MyThread 1 just selt one ticket,only 5 left
MyThread 1 just selt one ticket,only 4 left
MyThread num 2 just selt one ticket,only 4 left
MyThread 1 just selt one ticket,only 3 left
MyThread num 2 just selt one ticket,only 3 left
MyThread 1 just selt one ticket,only 2 left
MyThread num 2 just selt one ticket,only 2 left
MyThread 1 just selt one ticket,only 1 left
MyThread num 2 just selt one ticket,only 1 left
MyThread 1 just selt one ticket,only 0 left
MyThread num 2 just selt one ticket,only 0 left
可以看出,其实只有10张票,但两个线程分别卖了10张,共卖了20张。
当然也可以通过把tickets定义为static,即private static int tickets=10;也可以达到目的,只卖10张 票
用Runnable接口实现如下:
class MyThread implements Runnable{
public MyThread(String name){
super();
this.name=name;
}
public void run(){
while(tickets==0?false:true){
tickets--;
System.out.println(Thread.currentThread().getName()+" just selt one ticket,only "+tickets+" left");
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private String name;
private int tickets=10;
}
public class SellTicketsRunnable{
public static void main(String[] args){
MyThread aMyThread=new MyThread("My Thread");
new Thread(aMyThread).start();
new Thread(aMyThread).start();
}
}
打印接口如下:
Thread-0 just selt one ticket,only 9 left
Thread-1 just selt one ticket,only 8 left
Thread-0 just selt one ticket,only 7 left
Thread-1 just selt one ticket,only 6 left
Thread-0 just selt one ticket,only 5 left
Thread-1 just selt one ticket,only 4 left
Thread-0 just selt one ticket,only 3 left
Thread-1 just selt one ticket,only 2 left
Thread-0 just selt one ticket,only 1 left
Thread-1 just selt one ticket,only 0 left
可以看出虽然有两个线程,但两个线程的构造参数是同一个对象,访问的是同一个对象的资源。卖了10张票,达到了资源共享
java中利用继承类和Runnable接口实现多线程的区别