中文JAVA技術平等自由協作創造

          Java專題文章博客和開源

          常用鏈接

          統計

          最新評論

          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-15 11:35 好不容易 閱讀(172) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          PK10開獎 PK10開獎
          主站蜘蛛池模板: 五寨县| 北宁市| 昌平区| 柘荣县| 新绛县| 乐业县| 辽源市| 安陆市| 宜兰县| 克什克腾旗| 西丰县| 光泽县| 平果县| 南丰县| 兰考县| 丘北县| 澄迈县| 贵港市| 云梦县| 临猗县| 阿克陶县| 喀喇| 定陶县| 方正县| 乌兰察布市| 温泉县| 平武县| 达拉特旗| 高雄县| 沛县| 县级市| 阿拉善左旗| 精河县| 广饶县| 炉霍县| 湄潭县| 改则县| 呼和浩特市| 会昌县| 卢湾区| 鹤峰县|