来看看java中创建线程都有哪些方式!

一.继承Thread类创建线程类
可以通过继承 Thread 来创建一个线程类,该方法的好处是 this 代表的就是当前线程,不需要通过Thread.currentThread() 来获取当前线程的引用。

class MyThread extends Thread {
 @Override public void run() {
  System.out.println("这里是线程运行的代码"); 
  }
   }
MyThread t = new MyThread(); 
t.start(); // 线程开始运行

二. Runnable 接口
通过实现 Runnable 接口,并且调用 Thread 的构造方法时将 Runnable 对象作为 target 参数传入来创建线程对象。该方法的好处是可以规避类的单继承的限制;但需要通过 Thread.currentThread() 来获取当前线程的引用。

class MyRunnable implements Runnable { 
@Override public void run() { System.out.println(Thread.currentThread().getName() + "这里是线程运行的代码"); 
}
 }
Thread t = new Thread(new MyRunnable());
 t.start(); // 线程开始运行

三.创建线程-其他变形

// 使用匿名类创建 Thread 子类对象 
Thread t1 = new Thread() { 
@Override public void run() {
 System.out.println("使用匿名类创建 Thread 子类对象");
  }
   };
   // 使用匿名类创建 Runnable 子类对象
    Thread t2 = new Thread(new Runnable() {
     @Override public void run() {
      System.out.println("使用匿名类创建 Runnable 子类对象");
       }
      }
      ); 
        // 使用 lambda 表达式创建 Runnable 子类对象 
        Thread t3 = new Thread(() -> System.out.println("使用匿名类创建 Thread 子类对象")); 
        Thread t4 = new Thread(() -> { System.out.println("使用匿名类创建 Thread 子类对象"); });

猜你喜欢

转载自blog.csdn.net/weixin_45755718/article/details/106613235