1、联系:Thread相当于实现了Runnable的一个类,即public class Thread extends Object implements Runnable,发现Thread也是Runnable的一个子类。
2、区别:所谓的资源共享指的是成员变量,而不是成员函数
Thread:资源不共享,调用start(),重写run方法:
<pre name="code" class="java">package mythread;
/**
* Created by Administrator on 2015/10/31 0031.
*/
public class MyThread extends Thread{
public static void main(String[] args) {
MyThread mt1=new MyThread("Thread1");
MyThread mt2=new MyThread("Thread2");
mt1.start();
mt2.start();
}
String name="";
private int ticket=10;//ticket为共享资源
public MyThread(String name) {
super(name);
this.name=name;
}
public void run(){
for(int i=0;i<10;i++){
if(ticket>0)
System.out.println(this.name+" "+ticket--);
}
}
}
得出的结果是:每个线程都要卖10张票,而不是总共卖10张票
主函数可以直接调用run,也可以调用start,主要是因为在JDK安装路径下,scr.zip是java的源程序,通过代码可以看到thread。start()方法的定义,是底层的定义,即public native void start();
Runnable:是一个接口,可实现资源共享,
package Thread;
/**
* Created by Administrator on 2015/10/31 0031.
*/
public class MyRunnable implements Runnable{
private String name;
public void run() {
for(int i=0;i<10;i++){
System.out.println(this.name+" "+i);
}
}
public MyRunnable(String name) {
super();
this.name = name;
}
public static void main(String[] args) {
MyRunnable mr=new MyRunnable("MyRunnable");
new Thread( mr).start();
new Thread(mr).start();
new Thread( mr).start();
}
}
这样的结果也是每个线程进行10次,因为共享的是成员变量而不是函数,如果初始化了成员变量,那么重写run函数中这个成员变量为共享资源。
package mythread;
/**
* Created by Administrator on 2015/10/31 0031.
*/
public class MyRunnable implements Runnable{
private String name;
private int ticket=10;
public void run() {
for(int i=0;i<10;i++){
if(ticket>0)
System.out.println(Thread.currentThread().getName()+" "+ticket--);
}
}
public MyRunnable(String name) {
super();
this.name = name;
}
public static void main(String[] args) {
MyRunnable mr=new MyRunnable("MyRunnable");
new Thread(mr,"Thread1").start();
new Thread(mr,"Thread2").start();
new Thread(mr,"Thread3").start();
}
}
这样的话,得出的结果就是三个线程共享10,然后分配,即三个线程总共卖10张票
总结:其实Thread是接口Runnable的一个实现类,因此Thread不进行资源共享,而Runnable中只要在重写run是用到了成员变量,那么这个成员变量就是共享资源,所有线程共享资源。