步骤:
public class Test5 { public static void main(String[] args) { MyThread t1=new MyThread(); t1.start(); System.out.println(Thread.currentThread().getName()+"执行完成。"); } } class MyThread extends Thread{ @Override public void run(){ System.out.println(Thread.currentThread().getName()+"执行中。。。"); } }
步骤
/** * @description: Runnable接口有@FunctionalInterface,可以通过lamada创建 * @author: mufeng * @create: 2020/5/13 17:20 */ public class Test6 { public static void main(String[] args) { Thread t1=new Thread(()->{ System.out.println(Thread.currentThread().getName()+"执行中"); }); t1.start(); System.out.println(Thread.currentThread().getName()+"执行完成。"); } }
步骤
/** * @description: Callable接口有@FunctionalInterface,可以通过lamada创建 * @author: mufeng * @create: 2020/5/13 17:25 */ public class Test7 { public static void main(String[] args) { FutureTask<Integer> futureTask=new FutureTask(()->{ System.out.println(Thread.currentThread().getName()+"执行中"); return 1; }); Thread t1=new Thread(futureTask); t1.start(); try { System.out.println(Thread.currentThread().getName()+"结束:"+futureTask.get()); } catch (Exception e) { e.printStackTrace(); } } }
Executors提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口。
主要有newFixedThreadPool,newCachedThreadPool,newSingleThreadExecutor,newScheduledThreadPool
public class Test8 { public static void main(String[] args) { ExecutorService executorService = Executors.newSingleThreadExecutor(); for(int i=0;i<5;i++){ executorService.execute(()->{ System.out.println(Thread.currentThread().getName()+"执行中"); }); } System.out.println("线程任务开始执行"); executorService.shutdown(); } }
原文:https://www.cnblogs.com/mufeng07/p/12884003.html