- package com.zrun.TestThread;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class App {
- public static void main(String[] args) throws Exception, ExecutionException {
- System.out.println("主线程启动:"
- + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
- .format(new Date()));
- // 方式 1
- // ThreadEx thread1 = new ThreadEx();
- // thread1.start();
- // Thread.sleep(2000);
- // System.out.println("主线程执行结束:"
- // + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
- // .format(new Date()));
- // 方式 2
- // Thread thread2 = new Thread(new RunableEx());
- // thread2.start();
- // Thread.sleep(2000);
- // System.out.println("主线程执行结束:"
- // + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
- // .format(new Date()));
- // 方式 3
- // Callable<Object> oneCallable = new Thread3<Object>();
- // FutureTask<Object> oneTask = new FutureTask<Object>(oneCallable);
- // Thread t = new Thread(oneTask);
- // t.start();
- // Thread.sleep(2000);
- // System.out.println("主线程执行结束:"
- // + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
- // .format(new Date()));
- // // 主线程执行的 2 秒钟之后, 子线程只要再过 3 秒就结束了, 从而得到子线程的结果; 这里 get 方法会阻塞主线程
- // System.out.println(oneTask.get().toString());
- // 方式 4
- Thread4.test();
- Thread.sleep(2000);
- System.out.println("主线程执行结束:"
- + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
- .format(new Date()));
- }
- }
- // 方式 1: 继承 Thread 类
- class ThreadEx extends Thread {
- @Override
- public void run() {
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("子线程执行结束:"
- + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
- .format(new Date()));
- }
- }
- // 方式 2: 实现 Runnable 接口
- class RunableEx implements Runnable {
- public void run() {
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("子线程执行结束:"
- + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
- .format(new Date()));
- }
- }
- // 方式 3: 通过 Callable 和 FutureTask; 这种方式可以拿到子线程的返回值
- class Thread3<Object> implements Callable<Object> {
- @Override
- public Object call() throws Exception {
- Thread.sleep(5000);
- return (Object) ("我是子线程的返回值:" + new SimpleDateFormat(
- "yyyy-MM-dd HH:mm:ss").format(new Date()));
- }
- }
- // 方式 4: 通过线程池创建线程
- class Thread4 {
- static int POOL_NUM = 5;
- public static void test() {
- ExecutorService executorService = Executors.newFixedThreadPool(5);
- for (int i = 0; i < POOL_NUM; i++) {
- RunableEx thread = new RunableEx();
- executorService.execute(thread);
- }
- // 关闭线程池
- executorService.shutdown();
- }
- }
来源: http://www.bubuko.com/infodetail-2962352.html