• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            chenglong7997

            java中的多線程(轉(zhuǎn))

            java中的多線程
            在java中要想實(shí)現(xiàn)多線程,有兩種手段,一種是繼續(xù)Thread類(lèi),另外一種是實(shí)現(xiàn)Runable接口。
            對(duì)于直接繼承Thread的類(lèi)來(lái)說(shuō),代碼大致框架是:
            class 類(lèi)名 extends Thread{
            方法1;
            方法2;
            public void run(){
            // other code…
            }
            屬性1;
            屬性2;
             
            }
            先看一個(gè)簡(jiǎn)單的例子:
            /**
             * @author Rollen-Holt 繼承Thread類(lèi),直接調(diào)用run方法
             * */
            class hello extends Thread {
             
                public hello() {
             
                }
             
                public hello(String name) {
                    this.name = name;
                }
             
                public void run() {
                    for (int i = 0; i < 5; i++) {
                        System.out.println(name + "運(yùn)行     " + i);
                    }
                }
             
                public static void main(String[] args) {
                    hello h1=new hello("A");
                    hello h2=new hello("B");
                    h1.run();
                    h2.run();
                }
             
                private String name;
            }
            【運(yùn)行結(jié)果】:
            A運(yùn)行     0
            A運(yùn)行     1
            A運(yùn)行     2
            A運(yùn)行     3
            A運(yùn)行     4
            B運(yùn)行     0
            B運(yùn)行     1
            B運(yùn)行     2
            B運(yùn)行     3
            B運(yùn)行     4
            我們會(huì)發(fā)現(xiàn)這些都是順序執(zhí)行的,說(shuō)明我們的調(diào)用方法不對(duì),應(yīng)該調(diào)用的是start()方法。
            當(dāng)我們把上面的主函數(shù)修改為如下所示的時(shí)候:
            public static void main(String[] args) {
                    hello h1=new hello("A");
                    hello h2=new hello("B");
                    h1.start();
                    h2.start();
                }
            然后運(yùn)行程序,輸出的可能的結(jié)果如下:
            A運(yùn)行     0
            B運(yùn)行     0
            B運(yùn)行     1
            B運(yùn)行     2
            B運(yùn)行     3
            B運(yùn)行     4
            A運(yùn)行     1
            A運(yùn)行     2
            A運(yùn)行     3
            A運(yùn)行     4
            因?yàn)樾枰玫紺PU的資源,所以每次的運(yùn)行結(jié)果基本是都不一樣的,呵呵。
            注意:雖然我們?cè)谶@里調(diào)用的是start()方法,但是實(shí)際上調(diào)用的還是run()方法的主體。
            那么:為什么我們不能直接調(diào)用run()方法呢?
            我的理解是:線程的運(yùn)行需要本地操作系統(tǒng)的支持。
            如果你查看start的源代碼的時(shí)候,會(huì)發(fā)現(xiàn):
            public synchronized void start() {
                    /**
                 * This method is not invoked for the main method thread or "system"
                 * group threads created/set up by the VM. Any new functionality added 
                 * to this method in the future may have to also be added to the VM.
                 *
                 * A zero status value corresponds to state "NEW".
                     */
                    if (threadStatus != 0 || this != me)
                        throw new IllegalThreadStateException();
                    group.add(this);
                    start0();
                    if (stopBeforeStart) {
                    stop0(throwableFromStop);
                }
            }
            private native void start0();
            注意我用紅色加粗的那一條語(yǔ)句,說(shuō)明此處調(diào)用的是start0()。并且這個(gè)這個(gè)方法用了native關(guān)鍵字,次關(guān)鍵字表示調(diào)用本地操作系統(tǒng)的函數(shù)。因?yàn)槎嗑€程的實(shí)現(xiàn)需要本地操作系統(tǒng)的支持。
            但是start方法重復(fù)調(diào)用的話(huà),會(huì)出現(xiàn)java.lang.IllegalThreadStateException異常。
            通過(guò)實(shí)現(xiàn)Runnable接口:
             
            大致框架是:
            class 類(lèi)名 implements Runnable{
            方法1;
            方法2;
            public void run(){
            // other code…
            }
            屬性1;
            屬性2;
             
            }
            來(lái)先看一個(gè)小例子吧:
            /**
             * @author Rollen-Holt 實(shí)現(xiàn)Runnable接口
             * */
            class hello implements Runnable {
             
                public hello() {
             
                }
             
                public hello(String name) {
                    this.name = name;
                }
             
                public void run() {
                    for (int i = 0; i < 5; i++) {
                        System.out.println(name + "運(yùn)行     " + i);
                    }
                }
             
                public static void main(String[] args) {
                    hello h1=new hello("線程A");
                    Thread demo= new Thread(h1);
                    hello h2=new hello("線程B");
                    Thread demo1=new Thread(h2);
                    demo.start();
                    demo1.start();
                }
             
                private String name;
            }
            【可能的運(yùn)行結(jié)果】:
            線程A運(yùn)行     0
            線程B運(yùn)行     0
            線程B運(yùn)行     1
            線程B運(yùn)行     2
            線程B運(yùn)行     3
            線程B運(yùn)行     4
            線程A運(yùn)行     1
            線程A運(yùn)行     2
            線程A運(yùn)行     3
            線程A運(yùn)行     4
             
            關(guān)于選擇繼承Thread還是實(shí)現(xiàn)Runnable接口?
            其實(shí)Thread也是實(shí)現(xiàn)Runnable接口的:
            ?
            1
            2
            3
            4
            5
            6
            7
            8
            class Thread implements Runnable {
                //…
            public void run() {
                    if (target != null) {
                         target.run();
                    }
                    }
            }
            其實(shí)Thread中的run方法調(diào)用的是Runnable接口的run方法。不知道大家發(fā)現(xiàn)沒(méi)有,Thread和Runnable都實(shí)現(xiàn)了run方法,這種操作模式其實(shí)就是代理模式。關(guān)于代理模式,我曾經(jīng)寫(xiě)過(guò)一個(gè)小例子呵呵,大家有興趣的話(huà)可以看一下:http://www.cnblogs.com/rollenholt/archive/2011/08/18/2144847.html
            Thread和Runnable的區(qū)別:
            如果一個(gè)類(lèi)繼承Thread,則不適合資源共享。但是如果實(shí)現(xiàn)了Runable接口的話(huà),則很容易的實(shí)現(xiàn)資源共享。
            /**
             * @author Rollen-Holt 繼承Thread類(lèi),不能資源共享
             * */
            class hello extends Thread {
                public void run() {
                    for (int i = 0; i < 7; i++) {
                        if (count > 0) {
                            System.out.println("count= " + count--);
                        }
                    }
                }
             
                public static void main(String[] args) {
                    hello h1 = new hello();
                    hello h2 = new hello();
                    hello h3 = new hello();
                    h1.start();
                    h2.start();
                    h3.start();
                }
             
                private int count = 5;
            }
            【運(yùn)行結(jié)果】:
            count= 5
            count= 4
            count= 3
            count= 2
            count= 1
            count= 5
            count= 4
            count= 3
            count= 2
            count= 1
            count= 5
            count= 4
            count= 3
            count= 2
            count= 1
            大家可以想象,如果這個(gè)是一個(gè)買(mǎi)票系統(tǒng)的話(huà),如果count表示的是車(chē)票的數(shù)量的話(huà),說(shuō)明并沒(méi)有實(shí)現(xiàn)資源的共享。
            我們換為Runnable接口:
            /**
             * @author Rollen-Holt 繼承Thread類(lèi),不能資源共享
             * */
            class hello implements Runnable {
                public void run() {
                    for (int i = 0; i < 7; i++) {
                        if (count > 0) {
                            System.out.println("count= " + count--);
                        }
                    }
                }
             
                public static void main(String[] args) {
                    hello he=new hello();
                    new Thread(he).start();
                }
             
                private int count = 5;
            }
            【運(yùn)行結(jié)果】:
            count= 5
            count= 4
            count= 3
            count= 2
            count= 1
             
            總結(jié)一下吧:
            實(shí)現(xiàn)Runnable接口比繼承Thread類(lèi)所具有的優(yōu)勢(shì):
            1):適合多個(gè)相同的程序代碼的線程去處理同一個(gè)資源
            2):可以避免java中的單繼承的限制
            3):增加程序的健壯性,代碼可以被多個(gè)線程共享,代碼和數(shù)據(jù)獨(dú)立。
            所以,本人建議大家勁量實(shí)現(xiàn)接口。
            /**
             * @author Rollen-Holt 
             * 取得線程的名稱(chēng)
             * */
            class hello implements Runnable {
                public void run() {
                    for (int i = 0; i < 3; i++) {
                        System.out.println(Thread.currentThread().getName());
                    }
                }
             
                public static void main(String[] args) {
                    hello he = new hello();
                    new Thread(he,"A").start();
                    new Thread(he,"B").start();
                    new Thread(he).start();
                }
            }
            【運(yùn)行結(jié)果】:
            A
            A
            A
            B
            B
            B
            Thread-0
            Thread-0
            Thread-0
            說(shuō)明如果我們沒(méi)有指定名字的話(huà),系統(tǒng)自動(dòng)提供名字。
            提醒一下大家:main方法其實(shí)也是一個(gè)線程。在java中所以的線程都是同時(shí)啟動(dòng)的,至于什么時(shí)候,哪個(gè)先執(zhí)行,完全看誰(shuí)先得到CPU的資源。
             
            在java中,每次程序運(yùn)行至少啟動(dòng)2個(gè)線程。一個(gè)是main線程,一個(gè)是垃圾收集線程。因?yàn)槊慨?dāng)使用java命令執(zhí)行一個(gè)類(lèi)的時(shí)候,實(shí)際上都會(huì)啟動(dòng)一個(gè)JVM,每一個(gè)jVM實(shí)習(xí)在就是在操作系統(tǒng)中啟動(dòng)了一個(gè)進(jìn)程。
            判斷線程是否啟動(dòng)
            /**
             * @author Rollen-Holt 判斷線程是否啟動(dòng)
             * */
            class hello implements Runnable {
                public void run() {
                    for (int i = 0; i < 3; i++) {
                        System.out.println(Thread.currentThread().getName());
                    }
                }
             
                public static void main(String[] args) {
                    hello he = new hello();
                    Thread demo = new Thread(he);
                    System.out.println("線程啟動(dòng)之前---》" + demo.isAlive());
                    demo.start();
                    System.out.println("線程啟動(dòng)之后---》" + demo.isAlive());
                }
            }
            【運(yùn)行結(jié)果】
            線程啟動(dòng)之前---》false
            線程啟動(dòng)之后---》true
            Thread-0
            Thread-0
            Thread-0
            主線程也有可能在子線程結(jié)束之前結(jié)束。并且子線程不受影響,不會(huì)因?yàn)橹骶€程的結(jié)束而結(jié)束。
             
            線程的強(qiáng)制執(zhí)行:
            /**
                 * @author Rollen-Holt 線程的強(qiáng)制執(zhí)行
                 * */
                class hello implements Runnable {
                    public void run() {
                        for (int i = 0; i < 3; i++) {
                            System.out.println(Thread.currentThread().getName());
                        }
                    }
                 
                    public static void main(String[] args) {
                        hello he = new hello();
                        Thread demo = new Thread(he,"線程");
                        demo.start();
                        for(int i=0;i<50;++i){
                            if(i>10){
                                try{
                                    demo.join();  //強(qiáng)制執(zhí)行demo
                                }catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            System.out.println("main 線程執(zhí)行-->"+i);
                        }
                    }
                }
            【運(yùn)行的結(jié)果】:
            main 線程執(zhí)行-->0
            main 線程執(zhí)行-->1
            main 線程執(zhí)行-->2
            main 線程執(zhí)行-->3
            main 線程執(zhí)行-->4
            main 線程執(zhí)行-->5
            main 線程執(zhí)行-->6
            main 線程執(zhí)行-->7
            main 線程執(zhí)行-->8
            main 線程執(zhí)行-->9
            main 線程執(zhí)行-->10
            線程
            線程
            線程
            main 線程執(zhí)行-->11
            main 線程執(zhí)行-->12
            main 線程執(zhí)行-->13
            ...
             
            線程的休眠:
            /**
             * @author Rollen-Holt 線程的休眠
             * */
            class hello implements Runnable {
                public void run() {
                    for (int i = 0; i < 3; i++) {
                        try {
                            Thread.sleep(2000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + i);
                    }
                }
             
                public static void main(String[] args) {
                    hello he = new hello();
                    Thread demo = new Thread(he, "線程");
                    demo.start();
                }
            }
            【運(yùn)行結(jié)果】:(結(jié)果每隔2s輸出一個(gè))
            線程0
            線程1
            線程2
             
            線程的中斷:
            /**
             * @author Rollen-Holt 線程的中斷
             * */
            class hello implements Runnable {
                public void run() {
                    System.out.println("執(zhí)行run方法");
                    try {
                        Thread.sleep(10000);
                        System.out.println("線程完成休眠");
                    } catch (Exception e) {
                        System.out.println("休眠被打斷");
                        return;  //返回到程序的調(diào)用處
                    }
                    System.out.println("線程正常終止");
                }
             
                public static void main(String[] args) {
                    hello he = new hello();
                    Thread demo = new Thread(he, "線程");
                    demo.start();
                    try{
                        Thread.sleep(2000);
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                    demo.interrupt(); //2s后中斷線程
                }
            }
            【運(yùn)行結(jié)果】:
            執(zhí)行run方法
            休眠被打斷
             
            在java程序中,只要前臺(tái)有一個(gè)線程在運(yùn)行,整個(gè)java程序進(jìn)程不會(huì)小時(shí),所以此時(shí)可以設(shè)置一個(gè)后臺(tái)線程,這樣即使java進(jìn)程小時(shí)了,此后臺(tái)線程依然能夠繼續(xù)運(yùn)行。
            /**
             * @author Rollen-Holt 線程的優(yōu)先級(jí)
             * */
            class hello implements Runnable {
                public void run() {
                    for(int i=0;i<5;++i){
                        System.out.println(Thread.currentThread().getName()+"運(yùn)行"+i);
                    }
                }
             
                public static void main(String[] args) {
                    Thread h1=new Thread(new hello(),"A");
                    Thread h2=new Thread(new hello(),"B");
                    Thread h3=new Thread(new hello(),"C");
                    h1.setPriority(8);
                    h2.setPriority(2);
                    h3.setPriority(6);
                    h1.start();
                    h2.start();
                    h3.start();
                     
                }
            }
            【運(yùn)行結(jié)果】:
            A運(yùn)行0
            A運(yùn)行1
            A運(yùn)行2
            A運(yùn)行3
            A運(yùn)行4
            B運(yùn)行0
            C運(yùn)行0
            C運(yùn)行1
            C運(yùn)行2
            C運(yùn)行3
            C運(yùn)行4
            B運(yùn)行1
            B運(yùn)行2
            B運(yùn)行3
            B運(yùn)行4
            。但是請(qǐng)讀者不要誤以為優(yōu)先級(jí)越高就先執(zhí)行。誰(shuí)先執(zhí)行還是取決于誰(shuí)先去的CPU的資源、
             
            另外,主線程的優(yōu)先級(jí)是5.
            線程的禮讓。
            在線程操作中,也可以使用yield()方法,將一個(gè)線程的操作暫時(shí)交給其他線程執(zhí)行。
            /**
             * @author Rollen-Holt 線程的優(yōu)先級(jí)
             * */
            class hello implements Runnable {
                public void run() {
                    for(int i=0;i<5;++i){
                        System.out.println(Thread.currentThread().getName()+"運(yùn)行"+i);
                        if(i==3){
                            System.out.println("線程的禮讓");
                            Thread.currentThread().yield();
                        }
                    }
                }
             
                public static void main(String[] args) {
                    Thread h1=new Thread(new hello(),"A");
                    Thread h2=new Thread(new hello(),"B");
                    h1.start();
                    h2.start();
                     
                }
            }
            A運(yùn)行0
            A運(yùn)行1
            A運(yùn)行2
            A運(yùn)行3
            線程的禮讓
            A運(yùn)行4
            B運(yùn)行0
            B運(yùn)行1
            B運(yùn)行2
            B運(yùn)行3
            線程的禮讓
            B運(yùn)行4
             
             
            同步和死鎖:
            【問(wèn)題引出】:比如說(shuō)對(duì)于買(mǎi)票系統(tǒng),有下面的代碼:
            /**
             * @author Rollen-Holt 
             * */
            class hello implements Runnable {
                public void run() {
                    for(int i=0;i<10;++i){
                        if(count>0){
                            try{
                                Thread.sleep(1000);
                            }catch(InterruptedException e){
                                e.printStackTrace();
                            }
                            System.out.println(count--);
                        }
                    }
                }
             
                public static void main(String[] args) {
                    hello he=new hello();
                    Thread h1=new Thread(he);
                    Thread h2=new Thread(he);
                    Thread h3=new Thread(he);
                    h1.start();
                    h2.start();
                    h3.start();
                }
                private int count=5;
            }
            【運(yùn)行結(jié)果】:
            5
            4
            3
            2
            1
            0
            -1
            這里出現(xiàn)了-1,顯然這個(gè)是錯(cuò)的。,應(yīng)該票數(shù)不能為負(fù)值。
            如果想解決這種問(wèn)題,就需要使用同步。所謂同步就是在統(tǒng)一時(shí)間段中只有有一個(gè)線程運(yùn)行,
            其他的線程必須等到這個(gè)線程結(jié)束之后才能繼續(xù)執(zhí)行。
            【使用線程同步解決問(wèn)題】
            采用同步的話(huà),可以使用同步代碼塊和同步方法兩種來(lái)完成。
             
            【同步代碼塊】:
            語(yǔ)法格式:
            synchronized(同步對(duì)象){
             //需要同步的代碼
            }
            但是一般都把當(dāng)前對(duì)象this作為同步對(duì)象。
            比如對(duì)于上面的買(mǎi)票的問(wèn)題,如下:
            /**
             * @author Rollen-Holt 
             * */
            class hello implements Runnable {
                public void run() {
                    for(int i=0;i<10;++i){
                        synchronized (this) {
                            if(count>0){
                                try{
                                    Thread.sleep(1000);
                                }catch(InterruptedException e){
                                    e.printStackTrace();
                                }
                                System.out.println(count--);
                            }
                        }
                    }
                }
             
                public static void main(String[] args) {
                    hello he=new hello();
                    Thread h1=new Thread(he);
                    Thread h2=new Thread(he);
                    Thread h3=new Thread(he);
                    h1.start();
                    h2.start();
                    h3.start();
                }
                private int count=5;
            }
            【運(yùn)行結(jié)果】:(每一秒輸出一個(gè)結(jié)果)
            5
            4
            3
            2
            1
            【同步方法】
            也可以采用同步方法。
            語(yǔ)法格式為synchronized 方法返回類(lèi)型 方法名(參數(shù)列表){
                // 其他代碼
            }
            現(xiàn)在,我們采用同步方法解決上面的問(wèn)題。
            ?
            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20
            21
            22
            23
            24
            25
            26
            27
            28
            29
            30
            31
            32
            33
            /**
             * @author Rollen-Holt
             * */
            class hello implements Runnable {
                public void run() {
                    for (int i = 0; i < 10; ++i) {
                        sale();
                    }
                }
             
                public synchronized void sale() {
                    if (count > 0) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(count--);
                    }
                }
             
                public static void main(String[] args) {
                    hello he = new hello();
                    Thread h1 = new Thread(he);
                    Thread h2 = new Thread(he);
                    Thread h3 = new Thread(he);
                    h1.start();
                    h2.start();
                    h3.start();
                }
             
                private int count = 5;
            }
            【運(yùn)行結(jié)果】(每秒輸出一個(gè))
            5
            4
            3
            2
            1
            提醒一下,當(dāng)多個(gè)線程共享一個(gè)資源的時(shí)候需要進(jìn)行同步,但是過(guò)多的同步可能導(dǎo)致死鎖。
            此處列舉經(jīng)典的生產(chǎn)者和消費(fèi)者問(wèn)題。
            【生產(chǎn)者和消費(fèi)者問(wèn)題】
            先看一段有問(wèn)題的代碼。
            class Info {
             
                public String getName() {
                    return name;
                }
             
                public void setName(String name) {
                    this.name = name;
                }
             
                public int getAge() {
                    return age;
                }
             
                public void setAge(int age) {
                    this.age = age;
                }
             
                private String name = "Rollen";
                private int age = 20;
            }
             
            /**
             * 生產(chǎn)者
             * */
            class Producer implements Runnable{
                private Info info=null;
                Producer(Info info){
                    this.info=info;
                }
                 
                public void run(){
                    boolean flag=false;
                    for(int i=0;i<25;++i){
                        if(flag){
                            this.info.setName("Rollen");
                            try{
                                Thread.sleep(100);
                            }catch (Exception e) {
                                e.printStackTrace();
                            }
                            this.info.setAge(20);
                            flag=false;
                        }else{
                            this.info.setName("chunGe");
                            try{
                                Thread.sleep(100);
                            }catch (Exception e) {
                                e.printStackTrace();
                            }
                            this.info.setAge(100);
                            flag=true;
                        }
                    }
                }
            }
            /**
             * 消費(fèi)者類(lèi)
             * */
            class Consumer implements Runnable{
                private Info info=null;
                public Consumer(Info info){
                    this.info=info;
                }
                 
                public void run(){
                    for(int i=0;i<25;++i){
                        try{
                            Thread.sleep(100);
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
                        System.out.println(this.info.getName()+"<---->"+this.info.getAge());
                    }
                }
            }
             
            /**
             * 測(cè)試類(lèi)
             * */
            class hello{
                public static void main(String[] args) {
                    Info info=new Info();
                    Producer pro=new Producer(info);
                    Consumer con=new Consumer(info);
                    new Thread(pro).start();
                    new Thread(con).start();
                }
            }
            【運(yùn)行結(jié)果】:
            Rollen<---->100
            chunGe<---->20
            chunGe<---->100
            Rollen<---->100
            chunGe<---->20
            Rollen<---->100
            Rollen<---->100
            Rollen<---->100
            chunGe<---->20
            chunGe<---->20
            chunGe<---->20
            Rollen<---->100
            chunGe<---->20
            Rollen<---->100
            chunGe<---->20
            Rollen<---->100
            chunGe<---->20
            Rollen<---->100
            chunGe<---->20
            Rollen<---->100
            chunGe<---->20
            Rollen<---->100
            chunGe<---->20
            Rollen<---->100
            chunGe<---->20
            大家可以從結(jié)果中看到,名字和年齡并沒(méi)有對(duì)于。
             
            那么如何解決呢?
            1) 加入同步
            2) 加入等待和喚醒
            先來(lái)看看加入同步會(huì)是如何。
            class Info {
                 
                public String getName() {
                    return name;
                }
             
                public void setName(String name) {
                    this.name = name;
                }
             
                public int getAge() {
                    return age;
                }
             
                public void setAge(int age) {
                    this.age = age;
                }
             
                public synchronized void set(String name, int age){
                    this.name=name;
                    try{
                        Thread.sleep(100);
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                    this.age=age;
                }
                 
                public synchronized void get(){
                    try{
                        Thread.sleep(100);
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println(this.getName()+"<===>"+this.getAge());
                }
                private String name = "Rollen";
                private int age = 20;
            }
             
            /**
             * 生產(chǎn)者
             * */
            class Producer implements Runnable {
                private Info info = null;
             
                Producer(Info info) {
                    this.info = info;
                }
             
                public void run() {
                    boolean flag = false;
                    for (int i = 0; i < 25; ++i) {
                        if (flag) {
                             
                            this.info.set("Rollen", 20);
                            flag = false;
                        } else {
                            this.info.set("ChunGe", 100);
                            flag = true;
                        }
                    }
                }
            }
             
            /**
             * 消費(fèi)者類(lèi)
             * */
            class Consumer implements Runnable {
                private Info info = null;
             
                public Consumer(Info info) {
                    this.info = info;
                }
             
                public void run() {
                    for (int i = 0; i < 25; ++i) {
                        try {
                            Thread.sleep(100);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        this.info.get();
                    }
                }
            }
             
            /**
             * 測(cè)試類(lèi)
             * */
            class hello {
                public static void main(String[] args) {
                    Info info = new Info();
                    Producer pro = new Producer(info);
                    Consumer con = new Consumer(info);
                    new Thread(pro).start();
                    new Thread(con).start();
                }
            }
            【運(yùn)行結(jié)果】:
            Rollen<===>20
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            Rollen<===>20
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            ChunGe<===>100
            從運(yùn)行結(jié)果來(lái)看,錯(cuò)亂的問(wèn)題解決了,現(xiàn)在是Rollen 對(duì)應(yīng)20,ChunGe對(duì)于100
            ,但是還是出現(xiàn)了重復(fù)讀取的問(wèn)題,也肯定有重復(fù)覆蓋的問(wèn)題。如果想解決這個(gè)問(wèn)題,就需要使用Object類(lèi)幫忙了、
            ,我們可以使用其中的等待和喚醒操作。
            要完成上面的功能,我們只需要修改Info類(lèi)饑渴,在其中加上標(biāo)志位,并且通過(guò)判斷標(biāo)志位完成等待和喚醒的操作,代碼如下:
            class Info {
                 
                public String getName() {
                    return name;
                }
             
                public void setName(String name) {
                    this.name = name;
                }
             
                public int getAge() {
                    return age;
                }
             
                public void setAge(int age) {
                    this.age = age;
                }
             
                public synchronized void set(String name, int age){
                    if(!flag){
                        try{
                            super.wait();
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    this.name=name;
                    try{
                        Thread.sleep(100);
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                    this.age=age;
                    flag=false;
                    super.notify();
                }
                 
                public synchronized void get(){
                    if(flag){
                        try{
                            super.wait();
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                     
                    try{
                        Thread.sleep(100);
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println(this.getName()+"<===>"+this.getAge());
                    flag=true;
                    super.notify();
                }
                private String name = "Rollen";
                private int age = 20;
                private boolean flag=false;
            }
             
            /**
             * 生產(chǎn)者
             * */
            class Producer implements Runnable {
                private Info info = null;
             
                Producer(Info info) {
                    this.info = info;
                }
             
                public void run() {
                    boolean flag = false;
                    for (int i = 0; i < 25; ++i) {
                        if (flag) {
                             
                            this.info.set("Rollen", 20);
                            flag = false;
                        } else {
                            this.info.set("ChunGe", 100);
                            flag = true;
                        }
                    }
                }
            }
             
            /**
             * 消費(fèi)者類(lèi)
             * */
            class Consumer implements Runnable {
                private Info info = null;
             
                public Consumer(Info info) {
                    this.info = info;
                }
             
                public void run() {
                    for (int i = 0; i < 25; ++i) {
                        try {
                            Thread.sleep(100);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        this.info.get();
                    }
                }
            }
             
            /**
             * 測(cè)試類(lèi)
             * */
            class hello {
                public static void main(String[] args) {
                    Info info = new Info();
                    Producer pro = new Producer(info);
                    Consumer con = new Consumer(info);
                    new Thread(pro).start();
                    new Thread(con).start();
                }
            }
            【程序運(yùn)行結(jié)果】:
            Rollen<===>20
            ChunGe<===>100
            Rollen<===>20
            ChunGe<===>100
            Rollen<===>20
            ChunGe<===>100
            Rollen<===>20
            ChunGe<===>100
            Rollen<===>20
            ChunGe<===>100
            Rollen<===>20
            ChunGe<===>100
            Rollen<===>20
            ChunGe<===>100
            Rollen<===>20
            ChunGe<===>100
            Rollen<===>20
            ChunGe<===>100
            Rollen<===>20
            ChunGe<===>100
            Rollen<===>20
            ChunGe<===>100
            Rollen<===>20
            ChunGe<===>100
            Rollen<===>20
            先在看結(jié)果就可以知道,之前的問(wèn)題完全解決。

            posted on 2012-03-31 03:19 Snape 閱讀(211) 評(píng)論(0)  編輯 收藏 引用 所屬分類(lèi): Java

            導(dǎo)航

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

            統(tǒng)計(jì)

            常用鏈接

            留言簿

            隨筆分類(lèi)

            隨筆檔案

            文章分類(lèi)

            文章檔案

            my

            搜索

            最新評(píng)論

            閱讀排行榜

            評(píng)論排行榜

            久久中文字幕视频、最近更新| 久久精品国产亚洲AV高清热| 精品国产乱码久久久久久呢| 欧美亚洲国产精品久久| 香蕉99久久国产综合精品宅男自 | 久久99精品国产麻豆不卡| 久久国产精品免费| 人妻无码精品久久亚瑟影视| 精品无码久久久久久久动漫 | 99精品久久久久久久婷婷| 亚洲欧美日韩精品久久| 精品国产婷婷久久久| 久久精品国产男包| 色综合久久天天综合| 色婷婷综合久久久久中文一区二区| 国产精品日韩深夜福利久久| 国产精品视频久久久| 久久婷婷五月综合97色| 国产精品熟女福利久久AV | 亚洲国产精品一区二区久久| 精品国产99久久久久久麻豆| 久久久久国色AV免费观看| 亚洲国产成人久久精品动漫| 亚洲精品美女久久久久99小说| 国产精自产拍久久久久久蜜| 狠狠色婷婷久久综合频道日韩| 精品久久久久久无码人妻热| 久久96国产精品久久久| 国产成人精品久久免费动漫| 亚洲国产精品一区二区三区久久| 成人妇女免费播放久久久| 97精品久久天干天天天按摩| 99久久免费国产精品特黄| 国内精品久久久久久久久| 人妻精品久久久久中文字幕69| 久久人人青草97香蕉| 一级做a爰片久久毛片毛片| 久久久WWW免费人成精品| 精品久久久无码中文字幕天天| 精品无码久久久久久久久久| 久久亚洲电影|