多线程的实现方式

方式一:通过继承Thread类实现多线程

步骤:

  1、创建一个类继承Thread类;

  2、覆写Thread类的run()方法;

  3、创建Thread子类的实例,即创建了线程对象;

  4、调用线程对象的start()方法来启动该线程;

package study;

public class ThreadDemo {
    public static void main(String[] args) {
        new TestThread().start();
        for(int i=0;i<10;i++){
            System.out.println("main在运行");
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
class TestThread extends Thread{
    public void run(){
        for(int i=0;i<10;i++){
            System.out.println("TestThread在运行");
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

方式二:通过实现Runnable接口实现多线程

步骤:

  1、创建一个类实现Runnable接口;

  2、覆写Runnable接口的run()方法;

  3、创建Runnable实现类的实例,并以此实例作为Thread的target来创建Thread的对象,该Thread对象才是真正的线程对象;

  4、调用Thread对象的start()方法启动该线程;

package study;

public class ThreadDemo {
    public static void main(String[] args) {
        TestThread t=new TestThread();
        new Thread(t).start();//使用Thread类的start方法启动线程
        for(int i=0;i<10;i++){
            System.out.println("main在运行");
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
class TestThread implements Runnable{
    public void run(){
        for(int i=0;i<10;i++){
            System.out.println("TestThread在运行");
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

   实现Runnable接口相对于继承Thread类来说,有以下几个显著优势:

  1、避免由于Java的单继承特性带来的局限;

  2、可以使多个线程共享相同的资源,以达到资源共享的目的;

  

原文地址:https://www.cnblogs.com/Hellorxh/p/10886163.html