java中的多線程

java中要想實現多線程,有兩種手段,一種是繼續Thread類,另外一種是實現Runable接口。

對於直接繼承Thread的類來說,代碼大致框架是:

1
2
3
4
5
6
7
8
9
10
11
12
class類名 extendsThread{
方法1;
方法2;
publicvoidrun(){
// other code…
}
屬性1;
屬性2;
  
}

先看一個簡單的例子:

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
/**
 * @author Rollen-Holt 繼承Thread類,直接調用run方法
 * */
classhello extendsThread {
  
    publichello() {
  
    }
  
    publichello(String name) {
        this.name = name;
    }
  
    publicvoidrun() {
        for(inti = 0; i < 5; i++) {
            System.out.println(name + "運行     "+ i);
        }
    }
  
    publicstaticvoidmain(String[] args) {
        hello h1=newhello("A");
        hello h2=newhello("B");
        h1.run();
        h2.run();
    }
  
    privateString name;
}

【運行結果】:

A運行     0

A運行     1

A運行     2

A運行     3

A運行     4

B運行     0

B運行     1

B運行     2

B運行     3

B運行     4

我們會發現這些都是順序執行的,說明我們的調用方法不對,應該調用的是start()方法。

當我們把上面的主函數修改爲如下所示的時候:

1
2
3
4
5
6
publicstaticvoidmain(String[] args) {
        hello h1=newhello("A");
        hello h2=newhello("B");
        h1.start();
        h2.start();
    }

然後運行程序,輸出的可能的結果如下:

A運行     0

B運行     0

B運行     1

B運行     2

B運行     3

B運行     4

A運行     1

A運行     2

A運行     3

A運行     4

因爲需要用到CPU的資源,所以每次的運行結果基本是都不一樣的,呵呵。

注意:雖然我們在這裏調用的是start()方法,但是實際上調用的還是run()方法的主體。

那麼:爲什麼我們不能直接調用run()方法呢?

我的理解是:線程的運行需要本地操作系統的支持。

如果你查看start的源代碼的時候,會發現:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
publicsynchronizedvoidstart() {
        /**
     * 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)
            thrownewIllegalThreadStateException();
        group.add(this);
        start0();
        if(stopBeforeStart) {
        stop0(throwableFromStop);
    }
}
privatenativevoidstart0();

注意我用紅色加粗的那一條語句,說明此處調用的是start0()。並且這個這個方法用了native關鍵字,次關鍵字表示調用本地操作系統的函數。因爲多線程的實現需要本地操作系統的支持。

但是start方法重複調用的話,會出現java.lang.IllegalThreadStateException異常。

通過實現Runnable接口:

 

大致框架是:

1
2
3
4
5
6
7
8
9
10
11
12
class類名 implementsRunnable{
方法1;
方法2;
publicvoidrun(){
// other code…
}
屬性1;
屬性2;
  
}

來先看一個小例子吧:

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
/**
 * @author Rollen-Holt 實現Runnable接口
 * */
classhello implementsRunnable {
  
    publichello() {
  
    }
  
    publichello(String name) {
        this.name = name;
    }
  
    publicvoidrun() {
        for(inti = 0; i < 5; i++) {
            System.out.println(name + "運行     "+ i);
        }
    }
  
    publicstaticvoidmain(String[] args) {
        hello h1=newhello("線程A");
        Thread demo= newThread(h1);
        hello h2=newhello("線程B");
        Thread demo1=newThread(h2);
        demo.start();
        demo1.start();
    }
  
    privateString name;
}

【可能的運行結果】:

線程A運行     0

線程B運行     0

線程B運行     1

線程B運行     2

線程B運行     3

線程B運行     4

線程A運行     1

線程A運行     2

線程A運行     3

線程A運行     4

 

關於選擇繼承Thread還是實現Runnable接口?

其實Thread也是實現Runnable接口的

1
2
3
4
5
6
7
8
classThread implementsRunnable {
    //…
publicvoidrun() {
        if(target != null) {
             target.run();
        }
        }
}

其實Thread中的run方法調用的是Runnable接口的run方法。不知道大家發現沒有,ThreadRunnable都實現了run方法,這種操作模式其實就是代理模式。關於代理模式,我曾經寫過一個小例子呵呵,大家有興趣的話可以看一下:http://www.cnblogs.com/rollenholt/archive/2011/08/18/2144847.html

ThreadRunnable的區別:

如果一個類繼承Thread,則不適合資源共享。但是如果實現了Runable接口的話,則很容易的實現資源共享。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * @author Rollen-Holt 繼承Thread類,不能資源共享
 * */
classhello extendsThread {
    publicvoidrun() {
        for(inti = 0; i < 7; i++) {
            if(count > 0) {
                System.out.println("count= "+ count--);
            }
        }
    }
  
    publicstaticvoidmain(String[] args) {
        hello h1 = newhello();
        hello h2 = newhello();
        hello h3 = newhello();
        h1.start();
        h2.start();
        h3.start();
    }
  
    privateintcount = 5;
}

【運行結果】:

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

大家可以想象,如果這個是一個買票系統的話,如果count表示的是車票的數量的話,說明並沒有實現資源的共享。

我們換爲Runnable接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * @author Rollen-Holt 繼承Thread類,不能資源共享
 * */
classhello implementsRunnable {
    publicvoidrun() {
        for(inti = 0; i < 7; i++) {
            if(count > 0) {
                System.out.println("count= "+ count--);
            }
        }
    }
  
    publicstaticvoidmain(String[] args) {
        hello he=newhello();
        newThread(he).start();
    }
  
    privateintcount = 5;
}

【運行結果】:

count= 5

count= 4

count= 3

count= 2

count= 1

 

總結一下吧:

實現Runnable接口比繼承Thread類所具有的優勢:

1):適合多個相同的程序代碼的線程去處理同一個資源

2):可以避免java中的單繼承的限制

3):增加程序的健壯性,代碼可以被多個線程共享,代碼和數據獨立。

所以,本人建議大家勁量實現接口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * @author Rollen-Holt 
 * 取得線程的名稱
 * */
classhello implementsRunnable {
    publicvoidrun() {
        for(inti = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName());
        }
    }
  
    publicstaticvoidmain(String[] args) {
        hello he = newhello();
        newThread(he,"A").start();
        newThread(he,"B").start();
        newThread(he).start();
    }
}

【運行結果】:

A

A

A

B

B

B

Thread-0

Thread-0

Thread-0

說明如果我們沒有指定名字的話,系統自動提供名字。

提醒一下大家:main方法其實也是一個線程。在java中所以的線程都是同時啓動的,至於什麼時候,哪個先執行,完全看誰先得到CPU的資源。

 

java中,每次程序運行至少啓動2個線程。一個是main線程,一個是垃圾收集線程。因爲每當使用java命令執行一個類的時候,實際上都會啓動一個JVM,每一個jVM實習在就是在操作系統中啓動了一個進程。

判斷線程是否啓動

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * @author Rollen-Holt 判斷線程是否啓動
 * */
classhello implementsRunnable {
    publicvoidrun() {
        for(inti = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName());
        }
    }
  
    publicstaticvoidmain(String[] args) {
        hello he = newhello();
        Thread demo = newThread(he);
        System.out.println("線程啓動之前---》"+ demo.isAlive());
        demo.start();
        System.out.println("線程啓動之後---》"+ demo.isAlive());
    }
}

【運行結果】

線程啓動之前---false

線程啓動之後---true

Thread-0

Thread-0

Thread-0

主線程也有可能在子線程結束之前結束。並且子線程不受影響,不會因爲主線程的結束而結束。

 

線程的強制執行:

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
/**
     * @author Rollen-Holt 線程的強制執行
     * */
    classhello implementsRunnable {
        publicvoidrun() {
            for(inti = 0; i < 3; i++) {
                System.out.println(Thread.currentThread().getName());
            }
        }
      
        publicstaticvoidmain(String[] args) {
            hello he = newhello();
            Thread demo = newThread(he,"線程");
            demo.start();
            for(inti=0;i<50;++i){
                if(i>10){
                    try{
                        demo.join();  //強制執行demo
                    }catch(Exception e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("main 線程執行-->"+i);
            }
        }
    }

【運行的結果】:

main 線程執行-->0

main 線程執行-->1

main 線程執行-->2

main 線程執行-->3

main 線程執行-->4

main 線程執行-->5

main 線程執行-->6

main 線程執行-->7

main 線程執行-->8

main 線程執行-->9

main 線程執行-->10

線程

線程

線程

main 線程執行-->11

main 線程執行-->12

main 線程執行-->13

...

 

線程的休眠:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * @author Rollen-Holt 線程的休眠
 * */
classhello implementsRunnable {
    publicvoidrun() {
        for(inti = 0; i < 3; i++) {
            try{
                Thread.sleep(2000);
            } catch(Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + i);
        }
    }
  
    publicstaticvoidmain(String[] args) {
        hello he = newhello();
        Thread demo = newThread(he, "線程");
        demo.start();
    }
}

【運行結果】:(結果每隔2s輸出一個)

線程0

線程1

線程2

 

線程的中斷:

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
/**
 * @author Rollen-Holt 線程的中斷
 * */
classhello implementsRunnable {
    publicvoidrun() {
        System.out.println("執行run方法");
        try{
            Thread.sleep(10000);
            System.out.println("線程完成休眠");
        } catch(Exception e) {
            System.out.println("休眠被打斷");
            return;  //返回到程序的調用處
        }
        System.out.println("線程正常終止");
    }
  
    publicstaticvoidmain(String[] args) {
        hello he = newhello();
        Thread demo = newThread(he, "線程");
        demo.start();
        try{
            Thread.sleep(2000);
        }catch(Exception e) {
            e.printStackTrace();
        }
        demo.interrupt(); //2s後中斷線程
    }
}

【運行結果】:

執行run方法

休眠被打斷

 

java程序中,只要前臺有一個線程在運行,整個java程序進程不會小時,所以此時可以設置一個後臺線程,這樣即使java進程小時了,此後臺線程依然能夠繼續運行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
 * @author Rollen-Holt 後臺線程
 * */
classhello implementsRunnable {
    publicvoidrun() {
        while(true) {
            System.out.println(Thread.currentThread().getName() + "在運行");
        }
    }
  
    publicstaticvoidmain(String[] args) {
        hello he = newhello();
        Thread demo = newThread(he, "線程");
        demo.setDaemon(true);
        demo.start();
    }
}

雖然有一個死循環,但是程序還是可以執行完的。因爲在死循環中的線程操作已經設置爲後臺運行了。

線程的優先級:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * @author Rollen-Holt 線程的優先級
 * */
classhello implementsRunnable {
    publicvoidrun() {
        for(inti=0;i<5;++i){
            System.out.println(Thread.currentThread().getName()+"運行"+i);
        }
    }
  
    publicstaticvoidmain(String[] args) {
        Thread h1=newThread(newhello(),"A");
        Thread h2=newThread(newhello(),"B");
        Thread h3=newThread(newhello(),"C");
        h1.setPriority(8);
        h2.setPriority(2);
        h3.setPriority(6);
        h1.start();
        h2.start();
        h3.start();
          
    }
}

【運行結果】:

A運行0

A運行1

A運行2

A運行3

A運行4

B運行0

C運行0

C運行1

C運行2

C運行3

C運行4

B運行1

B運行2

B運行3

B運行4

。但是請讀者不要誤以爲優先級越高就先執行。誰先執行還是取決於誰先去的CPU的資源、

 

另外,主線程的優先級是5.

線程的禮讓。

在線程操作中,也可以使用yield()方法,將一個線程的操作暫時交給其他線程執行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * @author Rollen-Holt 線程的優先級
 * */
classhello implementsRunnable {
    publicvoidrun() {
        for(inti=0;i<5;++i){
            System.out.println(Thread.currentThread().getName()+"運行"+i);
            if(i==3){
                System.out.println("線程的禮讓");
                Thread.currentThread().yield();
            }
        }
    }
  
    publicstaticvoidmain(String[] args) {
        Thread h1=newThread(newhello(),"A");
        Thread h2=newThread(newhello(),"B");
        h1.start();
        h2.start();
          
    }
}

A運行0

A運行1

A運行2

A運行3

線程的禮讓

A運行4

B運行0

B運行1

B運行2

B運行3

線程的禮讓

B運行4

 

 

同步和死鎖:

【問題引出】:比如說對於買票系統,有下面的代碼:

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
/**
 * @author Rollen-Holt 
 * */
classhello implementsRunnable {
    publicvoidrun() {
        for(inti=0;i<10;++i){
            if(count>0){
                try{
                    Thread.sleep(1000);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println(count--);
            }
        }
    }
  
    publicstaticvoidmain(String[] args) {
        hello he=newhello();
        Thread h1=newThread(he);
        Thread h2=newThread(he);
        Thread h3=newThread(he);
        h1.start();
        h2.start();
        h3.start();
    }
    privateintcount=5;
}

【運行結果】:

5

4

3

2

1

0

-1

這裏出現了-1,顯然這個是錯的。,應該票數不能爲負值。

如果想解決這種問題,就需要使用同步。所謂同步就是在統一時間段中只有有一個線程運行,

其他的線程必須等到這個線程結束之後才能繼續執行。

【使用線程同步解決問題】

採用同步的話,可以使用同步代碼塊和同步方法兩種來完成。

 

【同步代碼塊】:

語法格式:

synchronized(同步對象){

 //需要同步的代碼

}

但是一般都把當前對象this作爲同步對象。

比如對於上面的買票的問題,如下:

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
/**
 * @author Rollen-Holt 
 * */
classhello implementsRunnable {
    publicvoidrun() {
        for(inti=0;i<10;++i){
            synchronized(this) {
                if(count>0){
                    try{
                        Thread.sleep(1000);
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(count--);
                }
            }
        }
    }
  
    publicstaticvoidmain(String[] args) {
        hello he=newhello();
        Thread h1=newThread(he);
        Thread h2=newThread(he);
        Thread h3=newThread(he);
        h1.start();
        h2.start();
        h3.start();
    }
    privateintcount=5;
}

【運行結果】:(每一秒輸出一個結果)

5

4

3

2

1

【同步方法】

也可以採用同步方法。

語法格式爲synchronized 方法返回類型 方法名(參數列表){

    // 其他代碼

}

現在,我們採用同步方法解決上面的問題。

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
 * */
classhello implementsRunnable {
    publicvoidrun() {
        for(inti = 0; i < 10; ++i) {
            sale();
        }
    }
  
    publicsynchronizedvoidsale() {
        if(count > 0) {
            try{
                Thread.sleep(1000);
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(count--);
        }
    }
  
    publicstaticvoidmain(String[] args) {
        hello he = newhello();
        Thread h1 = newThread(he);
        Thread h2 = newThread(he);
        Thread h3 = newThread(he);
        h1.start();
        h2.start();
        h3.start();
    }
  
    privateintcount = 5;
}

【運行結果】(每秒輸出一個)

5

4

3

2

1

提醒一下,當多個線程共享一個資源的時候需要進行同步,但是過多的同步可能導致死鎖。

此處列舉經典的生產者和消費者問題。

【生產者和消費者問題】

先看一段有問題的代碼。

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
classInfo {
  
    publicString getName() {
        returnname;
    }
  
    publicvoidsetName(String name) {
        this.name = name;
    }
  
    publicintgetAge() {
        returnage;
    }
  
    publicvoidsetAge(intage) {
        this.age = age;
    }
  
    privateString name = "Rollen";
    privateintage = 20;
}
  
/**
 * 生產者
 * */
classProducer implementsRunnable{
    privateInfo info=null;
    Producer(Info info){
        this.info=info;
    }
      
    publicvoidrun(){
        booleanflag=false;
        for(inti=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;
            }
        }
    }
}
/**
 * 消費者類
 * */
classConsumer implementsRunnable{
    privateInfo info=null;
    publicConsumer(Info info){
        this.info=info;
    }
      
    publicvoidrun(){
        for(inti=0;i<25;++i){
            try{
                Thread.sleep(100);
            }catch(Exception e) {
                e.printStackTrace();
            }
            System.out.println(this.info.getName()+"<---->"+this.info.getAge());
        }
    }
}
  
/**
 * 測試類
 * */
classhello{
    publicstaticvoidmain(String[] args) {
        Info info=newInfo();
        Producer pro=newProducer(info);
        Consumer con=newConsumer(info);
        newThread(pro).start();
        newThread(con).start();
    }
}

【運行結果】:

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

大家可以從結果中看到,名字和年齡並沒有對於。

 

那麼如何解決呢?

<!--[if !supportLists]-->1) <!--[endif]-->加入同步

<!--[if !supportLists]-->2) <!--[endif]-->加入等待和喚醒

先來看看加入同步會是如何。

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
classInfo {
      
    publicString getName() {
        returnname;
    }
  
    publicvoidsetName(String name) {
        this.name = name;
    }
  
    publicintgetAge() {
        returnage;
    }
  
    publicvoidsetAge(intage) {
        this.age = age;
    }
  
    publicsynchronizedvoidset(String name, intage){
        this.name=name;
        try{
            Thread.sleep(100);
        }catch(Exception e) {
            e.printStackTrace();
        }
        this.age=age;
    }
      
    publicsynchronizedvoidget(){
        try{
            Thread.sleep(100);
        }catch(Exception e) {
            e.printStackTrace();
        }
        System.out.println(this.getName()+"<===>"+this.getAge());
    }
    privateString name = "Rollen";
    privateintage = 20;
}
  
/**
 * 生產者
 * */
classProducer implementsRunnable {
    privateInfo info = null;
  
    Producer(Info info) {
        this.info = info;
    }
  
    publicvoidrun() {
        booleanflag = false;
        for(inti = 0; i < 25; ++i) {
            if(flag) {
                  
                this.info.set("Rollen", 20);
                flag = false;
            } else{
                this.info.set("ChunGe", 100);
                flag = true;
            }
        }
    }
}
  
/**
 * 消費者類
 * */
classConsumer implementsRunnable {
    privateInfo info = null;
  
    publicConsumer(Info info) {
        this.info = info;
    }
  
    publicvoidrun() {
        for(inti = 0; i < 25; ++i) {
            try{
                Thread.sleep(100);
            } catch(Exception e) {
                e.printStackTrace();
            }
            this.info.get();
        }
    }
}
  
/**
 * 測試類
 * */
classhello {
    publicstaticvoidmain(String[] args) {
        Info info = newInfo();
        Producer pro = newProducer(info);
        Consumer con = newConsumer(info);
        newThread(pro).start();
        newThread(con).start();
    }
}

【運行結果】:

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

從運行結果來看,錯亂的問題解決了,現在是Rollen 對應20ChunGe對於100

,但是還是出現了重複讀取的問題,也肯定有重複覆蓋的問題。如果想解決這個問題,就需要使用Object類幫忙了、

,我們可以使用其中的等待和喚醒操作。

要完成上面的功能,我們只需要修改Info類飢渴,在其中加上標誌位,並且通過判斷標誌位完成等待和喚醒的操作,代碼如下:

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
classInfo {
      
    publicString getName() {
        returnname;
    }
  
    publicvoidsetName(String name) {
        this.name = name;
    }
  
    publicintgetAge() {
        returnage;
    }
  
    publicvoidsetAge(intage) {
        this.age = age;
    }
  
    publicsynchronizedvoidset(String name, intage){
        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();
    }
      
    publicsynchronizedvoidget(){
        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();
    }
    privateString name = "Rollen";
    privateintage = 20;
    privatebooleanflag=false;
}
  
/**
 * 生產者
 * */
classProducer implementsRunnable {
    privateInfo info = null;
  
    Producer(Info info) {
        this.info = info;
    }
  
    publicvoidrun() {
        booleanflag = false;
        for(inti = 0; i < 25; ++i) {
            if(flag) {
                  
                this.info.set("Rollen", 20);
                flag = false;
            } else{
                this.info.set("ChunGe", 100);
                flag = true;
            }
        }
    }
}
  
/**
 * 消費者類
 * */
classConsumer implementsRunnable {
    privateInfo info = null;
  
    publicConsumer(Info info) {
        this.info = info;
    }
  
    publicvoidrun() {
        for(inti = 0; i < 25; ++i) {
            try{
                Thread.sleep(100);
            } catch(Exception e) {
                e.printStackTrace();
            }
            this.info.get();
        }
    }
}
  
/**
 * 測試類
 * */
classhello {
    publicstaticvoidmain(String[] args) {
        Info info = newInfo();
        Producer pro = newProducer(info);
        Consumer con = newConsumer(info);
        newThread(pro).start();
        newThread(con).start();
    }
}
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
【程序運行結果】:
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
先在看結果就可以知道,之前的問題完全解決。

《完》

PS(寫在後面):

本人深知學的太差,所以希望大家能多多指點。另外,關於多線程其實有很多的知識,由於目前我也就知道的不太多,寫了一些常用的。雖然在操作系統這門課上學了很多的線程和進程,比如銀行家算法等等的,以後有時間在補充,大家有什麼好資料可以留個言,大家一起分享一下,謝謝了。


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章