① 继承Thread类
② 重写run()方法
③ 调用start()方法开启线程
package com.example.myjava.javaMultithreading; /** * @Description: 多线程继承Thread类的实现 * @Author: Hanzao * @Date: 2022/01/14/17:10 */ public class LearnThread extends Thread{ @Override public void run(){ for(int i=0;i<100;i++){ System.out.println("子线程输出了"+i+this.getName()); } } public static void main(String[] args) { LearnThread thread1 = new LearnThread(); thread1.start(); LearnThread thread2 = new LearnThread(); thread2.start(); for(int i=0;i<10000;i++){ System.out.println(">>主线程输出了"+i); } } }
① 实现Runnable接口
② 重写run()方法
③ 执行线程需要丢入runnable接口实现类,调用start()方法
package com.example.myjava.javaMultithreading; /** * @Description: * @Author: Hanzao * @Date: 2022/01/14/19:39 */ public class LearnRunnable implements Runnable{ @Override public void run() { for(int i=0;i<100;i++){ System.out.println("子线程输出了:"+i+" "+Thread.currentThread().getName()); } } public static void main(String[] args) { LearnRunnable learnRunnable = new LearnRunnable(); new Thread(learnRunnable).start(); new Thread(learnRunnable).start(); for(int i=0;i<1000;i++){ System.out.println(">>主线程输出了:"+i); } } }
① 重写 call 方法
② 创建目标对象
③ 创建执行服务
④ 提交执行
⑤ 获取结果
⑥ 关闭服务
package com.example.myjava.javaMultithreading; import java.util.concurrent.*; /** * @Description: * @Author: Hanzao * @Date: 2022/01/14/20:24 */ public class LearnCallable implements Callable<String> { @Override public String call() { for(int i=0;i<100;i++){ System.out.println("子线程输出了"+i+Thread.currentThread().getName()); } return "OK!"; } public static void main(String[] args) throws ExecutionException, InterruptedException { LearnCallable learnCallable1 = new LearnCallable(); LearnCallable learnCallable2 = new LearnCallable(); LearnCallable learnCallable3 = new LearnCallable(); ExecutorService service = Executors.newFixedThreadPool(3); Future<String> r1 = service.submit(learnCallable1); Future<String> r2 = service.submit(learnCallable2); Future<String> r3 = service.submit(learnCallable3); String result1 = r1.get(); String result2 = r2.get(); String result3 = r3.get(); System.out.println(result1); System.out.println(result2); System.out.println(result3); service.shutdown(); } }