Java多线程的创建

Hello World, Hello Java Threads

Posted by Resulte on March 4, 2020

创建Java多线程的三种方式

Java使用java.lang.Thread类代表线程,所有的线程对象都必须是Thread类或其子类的实例。

每个线程的作用是完成一定的任务,实际上就是执行一段程序流即一段顺序执行的代码。

我简单归纳了Java中的几种建立方法:

1. 从 Thread派生一个自定义类,然后重写run()方法

步骤:

  • 定义Thread类的子类,并重写该类的run()方法,该run()方法的方法体就代表了线程需要完成的任务
  • 创建Thread子类的实例,即创建了线程对象
  • 调用线程对象的start()方法来启动该线程
public class Main {
    public static void main(String[] args) {
        Thread t = new MyThread();
        t.start(); // 启动新线程
    }
}
class MyThread extends Thread {
     // 重写run方法,完成该线程执行的逻辑
    @Override
    public void run() {
        System.out.println("run the new thread!");
    }
}

2. 创建Thread实例时,传入一个Runnable方法

步骤:

  • 定义Runnable接口的实现类,并重写该接口的run()方法
  • 创建Runnable实现类的实例,并以此实例作为Thread的target来创建Thread对象
  • 调用线程对象的start()方法来启动线程。
public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start(); // 启动新线程
    }
}

class MyRunnable implements Runnable {
    // 重写run方法,完成该线程执行的逻辑
    @Override
    public void run() {
        System.out.println("run the new thread!");
    }
}

当然,我们也可以非常优雅的用Lambda表达式简化一下~

public class Main {
    public static void main(String[] args) {
        Thread t = new Thread( () -> {
            System.out.println("run the new thread!");
        });
        t.start(); // 启动新线程
    }
}

同时,也要注意,实现Runnable接口比继承Thread类更具优势,更容易实现资源的共享,实现解耦操作,代码和线程独立。

3. 使用线程池建立线程

线程池其实就是一个容纳多个线程的容器,其中的线程可以反复使用,省去了频繁创建线程对象的操作, 无需反复创建线程而消耗过多资源。

使用线程池中线程对象的步骤:

  • 创建线程池对象,使用Executors类下的静态方法 ExecutorService newFixedThreadPool(int nThreads) 获取一个线程池ExecutorService 对象,其中参数为最大线程个数
  • 创建Runnable实现类的实例对象
  • 提交Runnable接口子类对象,使用线程池对象的submit(Runnable task)方法,执行线程
  • 关闭线程池(一般不做,因为线程池的目的就是反复利用)
public class MyRunnable implements Runnable { 
    @Override 
    public void run() { 
        System.out.println("run the new thread!"); 
    } 
}
public class Main {
    public static void main(String[] args) {
        // 创建线程池对象 
        ExecutorService service = Executors.newFixedThreadPool(2);//含2个线程对象 
        // 创建Runnable实例对象 
        MyRunnable r = new MyRunnable();
        // 从线程池中获取线程对象,然后调用MyRunnable中的run() 
        service.submit(r);
    }
}