并发编程-任务创建、执行-Demo
1.任务创建方式
1.1Runnable方式
/*** Runnable 任务 重写run方法** Runnable 接口的 run() 方法不能抛出任何受检查异常,只能在方法内部进行异常处理。* Callable 接口的 call() 方法可以抛出受检查异常,调用者需要进行相应的异常处理。*/
public class TaskRunnable implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + " 执行 Runnable 方法,没有返回值");}
}
1.2Callable方式
/*** Callable 任务 重写call方法*/
public class TaskCallable implements Callable {@Overridepublic Object call() throws Exception {// Thread.currentThread() 默认输出格式如下:// Thread[type-name,priority,group],其中://// type-name: 线程的名称。// priority: 线程的优先级(1-10,默认为5)。// group: 线程的组(通常是 main,表示主线程组)。System.out.println(Thread.currentThread().getName() + " 执行 Callable 任务,带返回值");return "Callable";}
}
1.3通过new Thread执行任务
Runnable任务可以直接使用Thread调用;
Callable任务需要先包装成FutureTask任务,然后使用Thread执行。
/*** 测试类,通过new Thread 执行任务*/
public class Main01 {public static void main(String[] args) throws ExecutionException, InterruptedException {Thread thread1 = new Thread(new TaskRunnable());// Thread只能创建Runnable方法,不能直接创建Callable方法FutureTask<String> futureTask = new FutureTask<>(new TaskCallable());// Callable方法 使用 FutureTask创建,然后使用线程执行Thread thread2 = new Thread(futureTask);thread1.start();thread2.start();System.out.println(futureTask.get());// 拿到Callable方法的返回值}
}
1.4通过线程池执行任务
线程池执行任务的方式有execute和submit。最大区别是:execute执行任务,无返回值;submit执行任务,有返回值。另外,execute方法会直接抛出异常,submit方法不会抛出异常,只有在通过Future的get方法获取结果的时候才会抛出异常
/*** 测试类,通过 ThreadPool线程池 执行任务*/
public class Main02 {public static void main(String[] args) throws ExecutionException, InterruptedException {ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(17,17,10,TimeUnit.SECONDS,new ArrayBlockingQueue<>(10),new ThreadFactory() {private int threadNum = 0;@Overridepublic Thread newThread(Runnable r) {// 给线程命名Thread thread = new Thread(r);thread.setName("myThread - " + threadNum);threadNum++;return thread;}},new ThreadPoolExecutor.AbortPolicy());threadPoolExecutor.execute(new TaskRunnable());// 通过execute直接执行Runnable任务Future<String> submit = threadPoolExecutor.submit(new TaskCallable());// 通过 submit,利用 Future 接收执行的返回值System.out.println(submit.get());threadPoolExecutor.shutdown();}
}
2.总结
创建任务的方式有:
1.实现Runnable接口,重写run方法;
2.实现Callable接口,重写call方法;
执行任务的方式:
1.使用Thread直接执行任务;
2.通过线程池执行任务。