qileilove

          blog已經轉移至github,大家請訪問 http://qaseven.github.io/

          Java多線程中使用synchronized說明

           1.在類中方法上加上
            synchronized關鍵字,是對整個對象加鎖,當一個線程訪問帶有synchronized的方法時,其他帶有synchronized的方法的訪問就都會阻塞。
            樣例:
          public class ThreadTest {
          public static void main(String[] args) {
          Stu stu = new Stu();
          StuThread1 t1 = new StuThread1(stu);
          t1.start();
          StuThread2 t2 = new StuThread2(stu);
          t2.start();
          }
          }
          class StuThread1 extends Thread {
          Stu stu;
          public StuThread1(Stu stu) {
          this.stu = stu;
          }
          public void run() {
          stu.read1();
          }
          }
          class StuThread2 extends Thread {
          Stu stu;
          public StuThread2(Stu stu) {
          this.stu = stu;
          }
          public void run() {
          stu.read2();
          }
          }
          class Stu {
          public synchronized void read1() {
          System.out.println("read1 begin");
          try {
          Thread.currentThread().sleep(2000);
          } catch (InterruptedException e) {
          e.printStackTrace();
          }
          System.out.println("read1 end");
          }
          public synchronized void read2() {
          System.out.println("read2 begin");
          try {
          Thread.currentThread().sleep(2000);
          } catch (InterruptedException e) {
          e.printStackTrace();
          }
          System.out.println("read2 end");
          }
          }
          打印結果為(兩個線程是順序執行的):
          read1 begin
          read1 end
          read2 begin
          read2 end
            如果去掉read2前面的synchronized關鍵字,打印為(線程出現了交叉執行):
          read1 begin
          read2 begin
          read2 end
          read1 end
            修改read2方法,
          public void read2() {
          synchronized(this)
          {
          System.out.println("read2 begin");
          try {
          Thread.currentThread().sleep(2000);
          } catch (InterruptedException e) {
          e.printStackTrace();
          }
          System.out.println("read2 end");
          }
          }
            對this進行加鎖,結果同一次,線程是順序執行的。

          posted on 2014-05-14 10:11 順其自然EVO 閱讀(174) 評論(0)  編輯  收藏 所屬分類: 測試學習專欄

          <2014年5月>
          27282930123
          45678910
          11121314151617
          18192021222324
          25262728293031
          1234567

          導航

          統計

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 汽车| 肃北| 闽清县| 六安市| 贵南县| 商都县| 朔州市| 镇雄县| 武穴市| 永平县| 鸡泽县| 寻甸| 张家川| 稷山县| 海阳市| 禹城市| 封丘县| 涿州市| 扶风县| 盐亭县| 射洪县| 黄山市| 闸北区| 芦溪县| 秦皇岛市| 安塞县| 西畴县| 苍溪县| 灵宝市| 西充县| 滦南县| 营山县| 乐平市| 潞西市| 乾安县| 皮山县| 牡丹江市| 镇赉县| 北海市| 赫章县| 尚义县|