您的位置:首页 > 编程语言 > Java开发

java 多线程实现方式Thread和Runnable之间差异

2016-03-01 11:04 489 查看
java中实现多线程的方式有两种,1种是继承Thread类,1种是实现Runable接口。平常我们是通过Runnable方式实现多线程,其实Thread也是实现的Runnable接口。可以查看Thread的源码。

1 public class Thread implements Runnable{
2 
3 }


通过继承Thread的方式,只需要继承Thread类,然后重写run方法,把线程运行的代码放在其中,调用start方法启动线程。

public class Main {
	public static void main(String arg[]){
		Person p1=new Person("p1");
		Person p2=new Person("p2");
		p1.start();
		p2.start();
	}
}
class Person extends Thread {
	private String name;
	Person(String s){
		name=s;
	}
	@Override
	public void run() {
		for(int i=0;i<50;i++)
			System.out.println(name+" is running");		
	}
}


Thread start方法如下

public synchronized void start() {
        /**
     * This method is not invoked for the main method thread or "system"
     * group threads created/set up by the VM. Any new functionality added 
     * to this method in the future may have to also be added to the VM.
     *
     * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();
        group.add(this);
        start0();
        if (stopBeforeStart) {
        stop0(throwableFromStop);
    }
}
这里主要是调用了start0方法,这时一个native本地调用,底层使用c语言实现

private native void start0();


2.Runnable接口

public class Main {
	public static void main(String arg[]){
		Runnable p1=new Person("p1");
		Runnable p2=new Person("p2");
		new Thread(p1).start();
		new Thread(p2).start();
	}
}
class Person implements Runnable {
	private String name;
	Person(String s){
		name=s;
	}
	@Override
	public void run() {
		for(int i=0;i<50;i++)
			System.out.println(name+" is running");		
	}
}
实现方式和继承Thread相似,不过Runnable没有Start方式,所以通过构造函数转成Thread(适配器模式)。

public Thread(Runnable target) {
     init(null, target, "Thread-" + nextThreadNum(), 0);
 }
Thread中有Runnable接口实现的引用(适配器设计模式);

private Runnable target;
当然还有其他的构造函数通过转换。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: