(2)创建线程的2种方式

创建线程

  • 继承Thread类
  • 实现Runnable接口

(1)继承Thread类

package Thread;

public class MyThread extends Thread{
    @Override
    public void run(){
        super.run();
        System.out.println("MyThread");
    }
}

 public static void main (String[] args){
        MyThread myThread = new MyThread();
        myThread.start();//耗时大
        System.out.println("运行结束!");
    }
    
------------------
运行结束!
MyThread
-------------------

线程的执行先后跟代码执行顺序无关

 public static void main (String[] args){
        MyThread myThread = new MyThread();
        myThread.start();//耗时大
        Thread.sleep(200);
        System.out.println("运行结束!");
    }
------------------
MyThread
运行结束!
-------------------

(2)实现Runnable接口

创建的线程类已经有一个父类了,就不能在继承Thread类,因为java不支持多继承
就只能实现Runnable接口

package
public class MyRunnable implements Runnable{
    @Override
    public void run(){
        System.out.println("运行中");
    }
}

 public static void main (String[] args){
       Runnable runnable = new MyRunnable();
       Thread thread = new Thread(runnable); 
        thread.start();//耗时大
        System.out.println("运行结束!");
    }
------------------
运行结束!
运行中
-------------------

你可能感兴趣的:(#,单线程与多线程,java,开发语言)