Java并发编程-1 基本线程机制

xiaoxiao2021-02-27  476

1 线程构造方法

方法1:通过Runnable接口描述线程任务

实现Runnable接口中的run方法 public class RunnableThread implements Runnable { public void run() { //Thread.MIN_PRIORITY,Thread.NORM_PRIORITY,Thread.MAX_PRIORITY//Thread.currentThread().setPriority(Thread.MAX_PRIORITY); Long thread_id = Thread.currentThread().getId(); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.print("this is RunnableThread, thread id = " + thread_id.toString() + '\n'); } } Long thread_id = Thread.currentThread().getId(); 通过Thread类启动RunnableThread线程 public class MyThread { public static void main(String[] args) throws ExecutionException, InterruptedException { RunnableThread runnableThread = new RunnableThread(); Thread thread = new Thread(runnableThread); thread.start(); System.out.print("main thread id is = " + Thread.currentThread().getId() + '\n'); thread.join(); } } 通过Executor执行器创建线程 public class MyThread { public static void main(String[] args) throws ExecutionException, InterruptedException { RunnableThread runnableThread = new RunnableThread(); ExecutorService exec_run = Executors.newCachedThreadPool(); for(int i = 0; i < 5; i++) { exec_run.execute(new RunnableThread()); } exec_run.shutdown(); } }

方法2:通过Callable接口创建可返回参数的任务

实现接口Callable中的call方法 import java.util.concurrent.*; import java.util.*; public class CallableThread implements Callable<String> { private int id; public CallableThread(int id) { this.id = id; } public String call() throws InterruptedException { long thread_id = Thread.currentThread().getId(); Thread.sleep(200); return "result of RunnableThread " + id + " thread id = " + thread_id; } } 通过Executor执行器执行 public class MyThread { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService exec_call = Executors.newCachedThreadPool(); ArrayList<Future<String>> futures = new ArrayList<Future<String>>(); for(int i = 0; i < 10; i++) futures.add(exec_call.submit(new CallableThread(i))); for(Future<String> fs : futures) System.out.print(fs.get() + '\n'); } }
转载请注明原文地址: https://www.6miu.com/read-389.html

最新回复(0)