public class MyThread extends Thread{ @Override public void run() { System.out.println("线程状态:" + Thread.currentThread().getState()); System.out.println("线程名称:" + Thread.currentThread().getName()); System.out.println("线程优先级:" + Thread.currentThread().getPriority()); } public static void main (String args []) { MyThread t = new MyThread(); t.start(); } }
输出:java
线程状态:RUNNABLE 线程名称:Thread-0 线程优先级:5
public class MyThread extends Thread { private int i = 0; public void run () { i++; System.out.println(i); } public static void main (String args []){ MyThread t = new MyThread(); t.start(); } }
1
public class MyRunnable implements Runnable { private int i =0; @Override public void run() { i++; System.out.println(i); } }
Test.java多线程
public class Test { public static void main (String args[]) { Thread t = new Thread(new MyRunnable()); t.start(); } }
输出并发
1
public interface Future<V> { V get () throws ...; // 当任务完成时, 获取结果 V get (long timeout, TimeUnit unit); // 在get方法的基础上指定了超时时间 void cancel ( boolean mayInterupt); // 取消任务的执行 boolean isDone (); // 任务是否已完成 boolean isCancel (); // 任务是否已取消 }
FutureTask task = new FutureTask(new Callable);
获得的task既是一个Runnable也是一个Future。这样一来,能够先把获得的task传入Thread构造函数中建立线程并运行(做为Runnable使用), 接着经过task.get以阻塞的方式得到返回值(做为Future使用)异步
import java.util.concurrent.Callable; public class MyCallable implements Callable { @Override public Object call() throws Exception { Thread.sleep(1000); return "返回值"; } }
Test.javaide
import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class Test { public static void main (String args []) throws ExecutionException, InterruptedException { // task同时实现了Runnable接口和Future接口 FutureTask task = new FutureTask(new MyCallable()); // 做为 Runnable 使用 Thread t = new Thread(task); t.start(); // 做为Future使用, 调用get方法时将阻塞直到得到返回值 System.out.println(task.get()); } }
返回值
public interface Executor { void execute(Runnable command); }
public interface ExecutorService extends Executor { void shutdown(); <T> Future<T> submit(Callable<T> task); <T> Future<T> submit(Runnable task, T result); // 其余方法 }
public class Executors { public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()); } public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); } }
public class MyRunnable implements Runnable{ @Override public void run() { for (int i=0;i<3;i++) { System.out.println("MyRunnable正在运行"); } } }
import java.util.concurrent.Callable; public class MyCallable implements Callable{ @Override public Object call() throws Exception { for (int i=0;i<3;i++) { System.out.println("MyCallable正在运行"); } return "回调参数"; } }
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Test { public static void main (String args []) throws ExecutionException, InterruptedException { // 建立一个固定数量为2的线程池 ExecutorService service = Executors.newFixedThreadPool(2); // 向线程池提交Callable任务,并将结果信息保存到Future中 Future callableFuture = service.submit(new MyCallable()); // 向线程池提交Runnable任务,并将结果信息保存到Future中 Future runnableFuture = service.submit(new MyRunnable()); // 输出结果信息 System.out.printf("MyCallable, 完成:%b取消:%b返回值:%s%n", callableFuture.isDone(), callableFuture.isCancelled(), callableFuture.get()); System.out.printf("MyRunnable, 完成:%b取消:%b返回值:%s%n", runnableFuture.isDone(), runnableFuture.isCancelled(), runnableFuture.get()); // 关闭线程池 service.shutdown(); } }
MyCallable正在运行 MyCallable正在运行 MyCallable正在运行 MyCallable, 完成:true取消:false返回值:回调参数 MyRunnable正在运行 MyRunnable正在运行 MyRunnable正在运行 MyRunnable, 完成:false取消:false返回值:null
public class InteruptSimulation implements Runnable{ private volatile static boolean stop = false; @Override public void run() { try { while (!stop) { System.out.println("线程正在运行"); // 休眠5秒 Thread.sleep(5000); } System.out.println("线程终止"); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main (String args []) throws InterruptedException { Thread t = new Thread(new InteruptSimulation()); t.start(); // 休眠1秒 Thread.sleep(1000); // 将共享变量stop置为true
System.out.println("发出终止线程的信号"); stop = true; } }
线程正在运行 发出终止线程的信号 // 约5s后输出 线程终止
public class InteruptReal implements Runnable{ @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { System.out.println("线程正在运行"); Thread.sleep(5000); } } catch (InterruptedException e) { // 发生中断异常后,中断状态位会被置为false,这里不作任何操做 } System.out.println("线程已中断"); } public static void main (String args []) throws InterruptedException { Thread t = new Thread(new InteruptReal()); t.start(); // 休眠1s Thread.sleep(1000); System.out.println("发出终止线程的信号"); t.interrupt(); } }
输出:函数
线程正在运行 发出终止线程的信号 // 当即输出 线程已中断
线程如今已经可以及时退出啦性能
public class InteruptReal implements Runnable{ @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { System.out.println("线程正在运行"); Thread.sleep(5000); } } catch (InterruptedException e) { System.out.println("中断状态位:"+Thread.currentThread().isInterrupted()); } } public static void main (String args []) throws InterruptedException { Thread t = new Thread(new InteruptReal()); t.start(); // 休眠1s Thread.sleep(1000); System.out.println("发出中断"); t.interrupt(); } }
输出:spa
线程正在运行 发出中断 中断状态位:false
public class JoinRunnable implements Runnable{ @Override public void run() { for(int i=0;i<3;i++) { System.out.println(Thread.currentThread().getName()+ "正在执行"); } } public static void main (String args[]) throws InterruptedException { Thread t = new Thread(new JoinRunnable()); t.start(); System.out.println("子线程执行完毕"); } }
子线程执行完毕 Thread-0正在执行 Thread-0正在执行 Thread-0正在执行
public class JoinRunnable implements Runnable{ @Override public void run() { for(int i=0;i<3;i++) { System.out.println(Thread.currentThread().getName()+ "正在执行"); } } public static void main (String args[]) throws InterruptedException { Thread t = new Thread(new JoinRunnable()); t.start(); t.join(); System.out.println("子线程执行完毕"); } }
输出:操作系统
Thread-0正在执行 Thread-0正在执行 Thread-0正在执行 子线程执行完毕