====== 线程状态图 ====== 参考:https://cyc2018.github.io/CS-Notes/#/notes/Java%20%E5%B9%B6%E5%8F%91 {{:java-concurrent:线程状态图.png?800*1200|}} ====== 多线程方式 ====== /** * 多线程实现的三种方式 * 1 实现Runnable接口 * 2 实现Callable接口 * 3 继承Thread类 * 实现接口会更好一些,因为: * Java 不支持多重继承,因此继承了 Thread 类就无法继承其它类,但是可以实现多个接口; * 类可能只要求可执行就行,继承整个 Thread 类开销过大。 */ public class MainUsingThread { public static void main(String[] args) throws ExecutionException, InterruptedException { MyRunnable myRunnable = new MyRunnable(); Thread threadA = new Thread(myRunnable); threadA.start(); MyCallable myCallable = new MyCallable(); FutureTask ft = new FutureTask<>(myCallable); Thread threadB = new Thread(ft); threadB.start(); System.out.println(ft.get()); MyThread myThread = new MyThread(); myThread.start(); } } public class MyCallable implements Callable { @Override public Integer call() { System.out.println("run my callable"); try { Thread.sleep(22000L); } catch (InterruptedException e) { System.out.println("I'm interrupted by others"); e.printStackTrace(); } finally { } return 123; } } public class MyRunnable implements Runnable { public void run(){ System.out.println("run my runnable"); try { Thread.sleep(21000L); } catch (InterruptedException e) { System.out.println("I'm interrupted by others"); e.printStackTrace(); } finally { } } } public class MyThread extends Thread { public void run() { System.out.println("run my thread"); try { Thread.sleep(20000L); } catch (InterruptedException e) { System.out.println("I'm interrupted by others"); e.printStackTrace(); } finally { } } } ====== 线程间通信 ======