Java多线程的实现方式
继承Thread ,实现Runnable, 实现Callable
callable有返回值
Thread
public class Test1_Thread { public static void main(String[] args) { new Test1_thread().start(); System.out.println("任务1已启动 "); new Test1_thread().start(); System.out.println("任务2已启动 "); } static class Test1_thread extends Thread { @Override public void run() { for (int j = 0; j < 5; j++) { Autil.w1s(1); Autil.printCurrent(j); } } } }
Runnable
public class Test2_Runnable { public static void main(String[] args) { new Thread(new Test2_myRunnable()).start(); System.out.println("任务1已启动 "); new Thread(new Test2_myRunnable()).start(); System.out.println("任务2已启动 "); } static class Test2_myRunnable implements Runnable { @Override public void run() { for (int j = 0; j < 5; j++) { Autil.w1s(1); Autil.printCurrent(j); } } } }
Callable
public class Test3_Callable { /** * 需要将任务交给线程池 */ public static void main(String[] args) throws Exception { // 1. 创建线程池 ExecutorService pool = Executors.newCachedThreadPool(); // 2. 向线程池提交任务 Future<Integer> future1 = pool.submit(new Test3_myCallable()); System.out.println("任务1已提交 "); // 3. 获取线程的返回值 System.out.println("------------------开始查询所有子线程的返回值 "); // --3.1 获取方式一: 阻塞方式等待返回值 // Integer j = future1.get(); int flag = 10; // --3.2 获取方式二,不停的询问线程任务是否执行完成了 while (10 == flag) { if (future1.isDone()) { flag = 6; System.out.println(" "); System.out.println(flag + "返回值为 " + future1.get()); } else { System.out.print("任务尚未完成 "); Thread.sleep(50); } } // 线程池运行结束后关闭 pool.shutdown(); System.out.println("运行结束 " + Thread.activeCount()); } static class Test3_myCallable implements Callable<Integer> { @Override public Integer call() throws Exception { Autil.w1s(1); Autil.printCurrentTimes(3); return 33; } } }
jdk1.7: fork_join
import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveTask; /** * 当工作量大时,对任务进行水平拆分。 */ public class Test9_fork { public static void main(String[] args) throws Exception { ForkJoinPool fjp = new ForkJoinPool(); Sum sum = new Sum(1, 1_0); ForkJoinTask<Long> task = fjp.submit(sum); System.out.println("提交完毕"); Long result = task.get(); System.out.println("输出结果" + result); } static class Sum extends RecursiveTask<Long> { private final long from; private final long to; Sum(long from, long to) { this.from = from; this.to = to; } static boolean tooBiger(long from, long to) { return (to - from) > 3 ? true : false; } static long sum(long from, long to) { long sum = 0; for (; from < to; from++) { sum += from; } return sum; } @Override protected Long compute() { if (tooBiger(from, to)) { // 任务量太大 long middle = (to + from) / 2; Sum sum1 = new Sum(from, middle); Sum sum2 = new Sum(middle, to); sum1.fork(); sum2.fork(); long sum = 0; sum = sum1.join() + sum2.join(); System.out.println(sum + " " + from + " > " + middle + " > " + to); return sum; } else { long sum = sum(from, to); System.out.println(sum + " == " + from + " > " + to); return sum; } } } }