同步鎖

同步鎖	
--1,概述
鎖是指  把共享資源 鎖住
同步是指 其餘線程 排隊等待鑰匙的現象
專門用來解決 多線程 中共享數據有隱患的問題
使用synchronized關鍵字表示鎖
在多線程編程裏, 有多條語句操做 了 共享資源 ,必定會有隱患!!!		
--2,用法
--用在方法上/同步方法
synchronized public void eat(){}
--用在代碼塊上/同步代碼塊
synchronized(鎖對象){.......}
--3,改造售票代碼
--implements Runnable

測試
public class C2 {
public static void main(String[] args) {
Ticket target = new Ticket();
Thread t = new Thread(target);
Thread t2 = new Thread(target);
Thread t3 = new Thread(target);
Thread t4 = new Thread(target);
t.start();
t2.start();
t3.start();
t4.start();
}
}

class Ticket implements Runnable{
int ticket = 100;
Object o = new Object();
String s ="13";
@Override
//TODO 1,如今因爲多線程 中,,對於共享資源進行了搶的操做,因此共享資源不安全
//能夠使用鎖 來保證安全,可是犧牲性能.synchronized表示鎖
//鎖能夠用在方法上也能夠用在代碼塊上.
//同步方法 synchronized public void run() {
//同步代碼塊 -- synchronized(鎖對象){有問題代碼}
public void run() {
while (true){
//TODO 2,同步代碼塊:須要考慮兩個問題
//1,鎖的位置(合理位置,從開始用到用完結束) 2,鎖對象(能夠任務,但必須是同一個對象)
//synchronized(new Object()){//四個線程new了4把鎖,不是同一個鎖對象,錯的
//synchronized(o){//同一個鎖對象,OK
//synchronized(s){//同一個鎖對象,OK synchronized (this) { if (ticket > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "--" + ticket--); } else { break; } } } }}
相關文章
相關標籤/搜索