Java 创建线程的 6 种基本写法

这里总结了 Java 创建线程的 6 种基本写法,包括:

  1. Runnable implements class;
  2. Runnable annonymous class;
  3. Runnable lambda;
  4. Thread extends;
  5. Thread anonymous + lambda;
  6. Simple Callable lambda(Callable/call 与 Runnable/run 同为接口,也有三种写法,此处记录最为流行的一种)。

Demo:

/**
 * Threads.java
 *
 * @author YanWen <i@yanwen.email>
 * @modified 2018-05-19
 */

import java.util.concurrent.*;

/**
 * Threads
 */
public class Threads {

  // Runnable styles
  /**
   * Old Runnable style
   */
  private class thread1 implements Runnable {
    @Override
    public void run() {
      System.out.println("Thread 1 (" +
        Thread.currentThread().getName() + ") is running");
    }
  };

  /**
   * Anonymous class style
   */
  private Runnable thread2 = new Runnable() {

    @Override
    public void run() {
      System.out.println("Thread 2 (" +
        Thread.currentThread().getName() + ") is running");
    }
  };

  /**
   * Lambda style
   */
  private Runnable thread3 = () -> {
    System.out.println("Thread 3 (" +
        Thread.currentThread().getName() + ") is running");
  };

  // Thread styles
  /**
   * Old Thread style
   */
  private class thread4 extends Thread {
    @Override
    public void run() {
      System.out.println("Thread 4 (" +
        Thread.currentThread().getName() + ") is running");
    }
  };

  /**
   * Anonymous + lambda style
   */
  private Thread thread5 = new Thread(() -> {
    System.out.println("Thread 5 (" +
        Thread.currentThread().getName() + ") is running");
  });

  // Callable/Future style
  /**
   * Callable
   */
  private Callable<String> thread6 = () -> {
    return "Thread 6 (" +
        Thread.currentThread().getName() + ") is running";
  };

  /**
   * Test
   */
  public void test() throws Exception {
    // Runnable, Thread
    System.out.println("Creating Executor Service 1 with a thread pool of Size 3...");
    ExecutorService executorService1 = Executors.newFixedThreadPool(3);

    System.out.println("Submitting the threads(1 ~ 5) for execution...");
    executorService1.submit(this.new thread1());
    executorService1.submit(thread2);
    executorService1.submit(thread3);
    executorService1.submit(this.new thread4());
    executorService1.submit(thread5);

    executorService1.shutdown();
    System.out.println("Executor Service 1 shutdown.");
    System.out.println();

    // Callbale
    ExecutorService executorService2 = Executors.newSingleThreadExecutor();

    System.out.println("Submitting Callable thread 6.");
    Future<String> future = executorService2.submit(thread6);

    System.out.println("Retrieve the result of the future:");
    // Future.get() blocks until the result is available
    String result = future.get();
    System.out.println(result);

    executorService2.shutdown();
    System.out.println("Executor Service 2 shutdown.");
    System.out.println();
  }

  /**
   * Main
   */
  public static void main(String[] args) {
    try {
      new Threads().test();
    } catch (Exception e) {
      //TODO: handle exception
      e.printStackTrace();
    }
  }
}

测试:

$ java Threads
Creating Executor Service 1 with a thread pool of Size 3...
Submitting the threads(1 ~ 5) for execution...
Thread 2 (pool-1-thread-2) is running
Thread 1 (pool-1-thread-1) is running
Thread 3 (pool-1-thread-3) is running
Thread 4 (pool-1-thread-1) is running
Thread 5 (pool-1-thread-2) is running
Executor Service 1 shutdown.

Submitting Callable thread 6.
Retrieve the result of the future:
Thread 6 (pool-2-thread-1) is running
Executor Service 2 shutdown.

参考:

  1. https://github.com/callicoder/java-concurrency-examples.git

作者: YanWen

Web 开发者

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s