Thread继承和Runnable接口创建多线程比较

By heiry on 2019-04-20 [ in 技术 ]

java中创建多线程主要是三种方式,1.继承Thread类,重写run方法 2.实现Runnable接口,重写run方法 3.实现Callable接口,重写call方法。最常用的是前两种,很多书上都提到2方式上的优势,理由是方便实现资源共享,代码和数据的分离,更好体现面向对象思想。实际上,我认为这两种没有太大区别,通过线程同步两者基本没什么差别,看个人习惯而已。

继承方式创建多线程:

public class ThreadDemo{
public static void main(String [] args){
new NewThread().start();
while(true){
System.out.println("main thread is running");
}
}
}
class NewThread extends Thread{
public void run(){ 
while(true){
System.out.println(Thread.currentThread().getName()+"is running");
}
}
}

Thread(Runnable target)是Thread类的构造方法,Runnable参数为接口类;

public class ThreadMain{
    public static void main(String [] args){
        ThreadRunable runableDemo = new ThreadRunable();
        Thread newThread = new Thread(runableDemo);
        newThread.start();
        while(true){
            System.out.println("main thread is running");
}
}
}
class ThreadRunable implements Runnable{
    public void run(){
        while(true){
            System.out.println(Thread.currentThread().getName()+"is running");
}
}
}

 

 

 >>



© 2009-2024 MOSANG.NET DESIGNED BY HEIRY