問:線程有哪些狀態?java
問:sleep和wait的區別?安全
最主要的本質區別:ide
Thread.java中的函數
Object.java中的oop
package interview.thread; /** * wait和sleep的區別 * @Author: cctv * @Date: 2019/5/17 11:49 */ public class WaitSleepDemo { public static void main(String[] args) { final Object lock = new Object(); new Thread(() -> { System.out.println("thread A is waiting to get lock"); synchronized (lock) { try { System.out.println("thread A get lock"); // 先等B運行起來再到下一步 Thread.sleep(20); System.out.println("thread A do wait method"); // wait讓出CPU和鎖 B會搶到鎖執行B後再執行A // lock.wait(1000); // sleep不會讓出鎖 A執行完了以後再執行B Thread.sleep(1000); System.out.println("thread A is done"); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); // 先啓動A拿到鎖,再讓B也運行 try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(() -> { System.out.println("thread B is waiting to get lock"); synchronized (lock) { try { System.out.println("thread B get lock"); System.out.println("thread B do wait method"); Thread.sleep(10); System.out.println("thread B is done"); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } }
sleep結果:測試
wait結果:線程
問:notify和notifyAll的區別?code
首先了解2個概念:對象
notifyAll會讓全部處於等待池的線程所有進入鎖池去競爭獲取鎖的機會blog
notify是隨機選擇一個處於等待池的線程進入鎖池去競爭獲取鎖的機會
問:yiled的含義?
當調用Thread.yield()函數時,會給線程調度器一個當前線程願意讓出CPU使用的暗示,可是線程調度器可能會忽略這個暗示。
yield並不會讓出當前佔用的鎖
問:如何中斷線程?
測試:
package interview.thread; /** * 中斷線程demo * * @Author: cctv * @Date: 2019/5/20 10:26 */ public class InterruptDemo { public static void main(String[] args) throws InterruptedException { Runnable interruptTask = new Runnable() { @Override public void run() { int i = 0; Thread t = Thread.currentThread(); // 加上註釋看阻塞狀態的處理 去掉註釋看工做狀態的處理 // try { while (!t.isInterrupted()) { // Thread.sleep(100); i++; System.out.println(t.getName() + "(" + t.getState() + ") loop " + i); } System.out.println(t.getName() + "(" + t.getState() + ") Thread isInterrupted is true. loop is" + i); // } catch (InterruptedException e) { // System.out.println(t.getName() + "(" + t.getState() + ") catch InterruptedException. loop is " + i); // } } }; Thread t1 = new Thread(interruptTask, "t1"); System.out.println(t1.getName() + "(" + t1.getState() + ") is new"); t1.start(); System.out.println(t1.getName() + "(" + t1.getState() + ") is started"); Thread.sleep(300); t1.interrupt(); System.out.println(t1.getName() + "(" + t1.getState() + ") is interrupted"); Thread.sleep(300); System.out.println(t1.getName() + "(" + t1.getState() + ") is terminated"); } }