1. 程式人生 > >進程與線程(一)=====>線程安全

進程與線程(一)=====>線程安全

locks 出錯 .get start string 異常 interrupt str 生成

1.並發訪問(同一個時間段內執行)<====>並行(同時刻)
2.Thread.sleep(1000);//當前線程睡1秒(1000毫秒)當前線程休息,其他線程先占用資源
3.子類覆蓋父類方法 子類不能拋出新的異常 只能使用Try-cache方法
4.synchronized 不能修飾 run方法 因為修飾過之後 就執行完了

線程安全 1.synchronized 2.線程鎖 lock

實例:1.synchronized 也可以作為一個修飾符放在類或者方法前面 但是 要做到 範圍盡可能的小 所以用下面的代碼塊

synchronized(){
/*要執要執行的資源*/
}

  2.synchronized

package xiancheng;
/*解決方法
 * 1.同步代碼塊
 * 2.同步方法
 * 3.鎖機制【同步鎖:同步監聽對象,互斥鎖,同步監聽鎖】
 */
class Chi implements Runnable{
	public static int num=100;
	public void run() {
		for (int i = 0; i < 100; i++) {
			synchronized(this){//小括號內可以放Chi.class【我也不知道為什麽】
				try {
					Thread.sleep(20);
				} catch (InterruptedException e) {
					// TODO 自動生成的 catch 塊
					e.printStackTrace();
				}
				if(num>0) {
					System.out.println(Thread.currentThread().getName()+"吃了第"+num--+"個蘋果");
				}
			}
		}
	}
}

public class Youxi {
   public static  void main(String[] args) {
	      Chi a = new Chi();
	      new Thread(a,"小A").start();
	      new Thread(a,"小B").start();
	      new Thread(a,"小C").start();
	      
	      
   }
}

  2. lock====>創建對象 獲取鎖 釋放鎖 try-catch-finally 【父類中沒有拋出錯誤子類中就不能拋出錯誤 只能使用try catch】

package xiancheng;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*解決方法
 * 1.同步代碼塊
 * 2.同步方法
 * 3.鎖機制【同步鎖:同步監聽對象,互斥鎖,同步監聽鎖】
 */
class Chi implements Runnable{
	public static int num=100;
	private final Lock  lock = new ReentrantLock();
	public void run() {
		for (int i = 0; i < 100; i++) {
			lock.lock();
				try {
					Thread.sleep(20);
					if(num>0) {
						System.out.println(Thread.currentThread().getName()+"吃了第"+num--+"個蘋果");
					}
				} catch (InterruptedException e) {
					// TODO 自動生成的 catch 塊
					e.printStackTrace();
				}
				finally {
					lock.unlock();
				}
				
			
		}
	}
}

public class Youxi {
   public static  void main(String[] args) {
	      Chi a = new Chi();
	      new Thread(a,"小A").start();
	      new Thread(a,"小B").start();
	      new Thread(a,"小C").start();
	      
	      
   }
}

  

進程與線程(一)=====>線程安全