1. 程式人生 > >02.第二階段、實戰Java高併發程式設計模式-2.併發基礎

02.第二階段、實戰Java高併發程式設計模式-2.併發基礎

 什麼是執行緒
 執行緒的基本操作
 守護執行緒
 執行緒優先順序
 基本的執行緒同步操作
  1. 什麼是執行緒

  2. 執行緒的基本操作

  3. 執行緒中斷

    	public static native void sleep(long millis) throws InterruptedException
    	public void run(){ while(true){
    	  } }
    	if(Thread.currentThread().isInterrupted()){ System.out.println("Interruted!");
    	break; }
    	try {
    	Thread.sleep(2000);
    	} catch (InterruptedException e) {
    	System.out.println("Interruted When Sleep"); //設定中斷狀態,丟擲異常後會清除中斷標記位 Thread.currentThread().interrupt();
    	} Thread.yield();
    

  4. 守護執行緒

  5. 執行緒優先順序

  6. 執行緒同步

    	public class ThreadTest {
    
    		public static Object object = new Object();
    
    		public static class T2 extends Thread {
    			public void run() {
    				synchronized (object) {
    					System.out.println(System.currentTimeMillis() + ":T2 start! notify one thread");
    					object.notify();
    					System.out.println(System.currentTimeMillis() + ":T2 end!");
    					try {
    						Thread.sleep(2000);
    					} catch (InterruptedException e) {
    					}
    				}
    			}
    		}
    
    		public static class T1 extends Thread {
    			public void run() {
    				synchronized (object) {
    					System.out.println(System.currentTimeMillis() + ":T1 start! ");
    					try {
    						System.out.println(System.currentTimeMillis() + ":T1 wait for object ");
    						object.wait();
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					System.out.println(System.currentTimeMillis() + ":T1 end!");
    				}
    			}
    		}
    
    		public static void main(String[] args) {
    			T1 t1 = new T1();
    			t1.start();
    			T2 t2 = new T2();
    			t2.start();
    		}
    
    	}