中文JAVA技術(shù)平等自由協(xié)作創(chuàng)造

          Java專題文章博客和開源

          常用鏈接

          統(tǒng)計(jì)

          最新評論

          Java多線程中使用synchronized說明

            1.在類中方法上加上
            synchronized關(guān)鍵字,是對整個(gè)對象加鎖,當(dāng)一個(gè)線程訪問帶有synchronized的方法時(shí),其他帶有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");
            }
            }
            打印結(jié)果為(兩個(gè)線程是順序執(zhí)行的):
            read1 begin
            read1 end
            read2 begin
            read2 end
            如果去掉read2前面的synchronized關(guān)鍵字,打印為(線程出現(xiàn)了交叉執(zhí)行):
            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進(jìn)行加鎖,結(jié)果同一次,線程是順序執(zhí)行的托福答案

          posted on 2014-05-15 11:35 好不容易 閱讀(181) 評論(0)  編輯  收藏


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


          網(wǎng)站導(dǎo)航:
           
          PK10開獎(jiǎng) PK10開獎(jiǎng)
          主站蜘蛛池模板: 溧阳市| 嘉禾县| 广灵县| 教育| 永吉县| 秭归县| 莱芜市| 祥云县| 拜泉县| 台江县| 深水埗区| 海阳市| 岳阳县| 镇原县| 聂拉木县| 盘山县| 南宫市| 唐山市| 台南市| 香格里拉县| 梅州市| 通许县| 蚌埠市| 阿拉尔市| 丹巴县| 灵宝市| 辽源市| 千阳县| 台州市| 遵义市| 杨浦区| 斗六市| 兴国县| 会理县| 阳原县| 镇江市| 新兴县| 镇安县| 乌兰察布市| 灵山县| 南澳县|