java基礎學習總結——線程(二)


一、線程的優先級別

  

線程優先級別的使用范例:

 1 package cn.galc.test;
 2 
 3 public class TestThread6 {
 4     public static void main(String args[]) {
 5         MyThread4 t4 = new MyThread4();
 6         MyThread5 t5 = new MyThread5();
 7         Thread t1 = new Thread(t4);
 8         Thread t2 = new Thread(t5);
 9         t1.setPriority(Thread.NORM_PRIORITY + 3);// 使用setPriority()方法設置線程的優先級別,這里把t1線程的優先級別進行設置
10         /*
11          * 把線程t1的優先級(priority)在正常優先級(NORM_PRIORITY)的基礎上再提高3級 
12          * 這樣t1的執行一次的時間就會比t2的多很多     
13          * 默認情況下NORM_PRIORITY的值為5
14          */
15         t1.start();
16         t2.start();
17         System.out.println("t1線程的優先級是:" + t1.getPriority());
18         // 使用getPriority()方法取得線程的優先級別,打印出t1的優先級別為8
19     }
20 }
21 
22 class MyThread4 implements Runnable {
23     public void run() {
24         for (int i = 0; i <= 1000; i++) {
25             System.out.println("T1:" + i);
26         }
27     }
28 }
29 
30 class MyThread5 implements Runnable {
31     public void run() {
32         for (int i = 0; i <= 1000; i++) {
33             System.out.println("===============T2:" + i);
34         }
35     }
36 }

  run()方法一結束,線程也就結束了。

二、線程同步

  

synchronized關鍵字的使用范例:

 1 package cn.galc.test;
 2 
 3 public class TestSync implements Runnable {
 4     Timer timer = new Timer();
 5 
 6     public static void main(String args[]) {
 7         TestSync test = new TestSync();
 8         Thread t1 = new Thread(test);
 9         Thread t2 = new Thread(test);
10         t1.setName("t1");// 設置t1線程的名字
11         t2.setName("t2");// 設置t2線程的名字
12         t1.start();
13         t2.start();
14     }
15 
16     public void run() {
17         timer.add(Thread.currentThread().getName());
18     }
19 }
20 
21 class Timer {
22     private static int num = 0;
23 
24     public/* synchronized */void add(String name) {// 在聲明方法時加入synchronized時表示在執行這個方法的過程之中當前對象被鎖定
25         synchronized (this) {
26             /*
27              * 使用synchronized(this)來鎖定當前對象,這樣就不會再出現兩個不同的線程同時訪問同一個對象資源的問題了 只有當一個線程訪問結束后才會輪到下一個線程來訪問
28              */
29             num++;
30             try {
31                 Thread.sleep(1);
32             } catch (InterruptedException e) {
33                 e.printStackTrace();
34             }
35             System.out.println(name + ":你是第" + num + "個使用timer的線程");
36         }
37     }
38 }

線程死鎖的問題:

 1 package cn.galc.test;
 2 
 3 /*這個小程序模擬的是線程死鎖的問題*/
 4 public class TestDeadLock implements Runnable {
 5     public int flag = 1;
 6     static Object o1 = new Object(), o2 = new Object();
 7 
 8     public void run() {
 9         System.out.println(Thread.currentThread().getName() + "的flag=" + flag);
10         /*
11          * 運行程序后發現程序執行到這里打印出flag以后就再也不往下執行后面的if語句了 
12          * 程序也就死在了這里,既不往下執行也不退出
13          */
14 
15         /* 這是flag=1這個線程 */
16         if (flag == 1) {
17             synchronized (o1) {
18                 /* 使用synchronized關鍵字把對象01鎖定了 */
19                 try {
20                     Thread.sleep(500);
21                 } catch (InterruptedException e) {
22                     e.printStackTrace();
23                 }
24                 synchronized (o2) {
25                     /*
26                      * 前面已經鎖住了對象o1,只要再能鎖住o2,那么就能執行打印出1的操作了 
27                      * 可是這里無法鎖定對象o2,因為在另外一個flag=0這個線程里面已經把對象o1給鎖住了 
28                      * 盡管鎖住o2這個對象的線程會每隔500毫秒睡眠一次,可是在睡眠的時候仍然是鎖住o2不放的
29                      */
30                     System.out.println("1");
31                 }
32             }
33         }
34         /*
35          * 這里的兩個if語句都將無法執行,因為已經造成了線程死鎖的問題 
36          * flag=1這個線程在等待flag=0這個線程把對象o2的鎖解開, 
37          * 而flag=0這個線程也在等待flag=1這個線程把對象o1的鎖解開 
38          * 然而這兩個線程都不願意解開鎖住的對象,所以就造成了線程死鎖的問題
39          */
40 
41         /* 這是flag=0這個線程 */
42         if (flag == 0) {
43             synchronized (o2) {
44                 /* 這里先使用synchronized鎖住對象o2 */
45                 try {
46                     Thread.sleep(500);
47                 } catch (InterruptedException e) {
48                     e.printStackTrace();
49                 }
50                 synchronized (o1) {
51                     /*
52                      * 前面已經鎖住了對象o2,只要再能鎖住o1,那么就能執行打印出0的操作了 可是這里無法鎖定對象o1,因為在另外一個flag=1這個線程里面已經把對象o1給鎖住了 盡管鎖住o1這個對象的線程會每隔500毫秒睡眠一次,可是在睡眠的時候仍然是鎖住o1不放的
53                      */
54                     System.out.println("0");
55                 }
56             }
57         }
58     }
59 
60     public static void main(String args[]) {
61         TestDeadLock td1 = new TestDeadLock();
62         TestDeadLock td2 = new TestDeadLock();
63         td1.flag = 1;
64         td2.flag = 0;
65         Thread t1 = new Thread(td1);
66         Thread t2 = new Thread(td2);
67         t1.setName("線程td1");
68         t2.setName("線程td2");
69         t1.start();
70         t2.start();
71     }
72 }

  解決線程死鎖的問題最好只鎖定一個對象,不要同時鎖定兩個對象

生產者消費者問題:

 1 package cn.galc.test;
 2 
 3 /*    范例名稱:生產者--消費者問題
 4  *     源文件名稱:ProducerConsumer.java
 5  *    要  點:
 6  *        1. 共享數據的不一致性/臨界資源的保護
 7  *        2. Java對象鎖的概念
 8  *        3. synchronized關鍵字/wait()及notify()方法
 9  */
10 
11 public class ProducerConsumer {
12     public static void main(String args[]){
13             SyncStack stack = new SyncStack();
14             Runnable p=new Producer(stack);
15             Runnable c = new Consumer(stack);
16             Thread p1 = new Thread(p);
17             Thread c1 = new Thread(c);
18             
19             p1.start();
20             c1.start();
21     }
22 }
23 
24 
25 class SyncStack{  //支持多線程同步操作的堆棧的實現
26     private int index = 0;
27     private char []data = new char[6];    
28     public synchronized void push(char c){
29         if(index == data.length){
30         try{
31                 this.wait();
32         }catch(InterruptedException e){}
33         }
34         this.notify();
35         data[index] = c;
36         index++;
37     }
38     public synchronized char pop(){
39         if(index ==0){
40             try{
41                 this.wait();
42             }catch(InterruptedException e){}
43         }
44         this.notify();
45         index--;
46         return data[index];
47     }
48 }
49 
50 
51 class  Producer implements Runnable{
52     SyncStack stack;    
53     public Producer(SyncStack s){
54         stack = s;
55     }
56     public void run(){
57         for(int i=0; i<20; i++){
58             char c =(char)(Math.random()*26+'A');
59             stack.push(c);
60             System.out.println("produced:"+c);
61             try{                                    
62                 Thread.sleep((int)(Math.random()*1000)); 
63             }catch(InterruptedException e){
64             }
65         }
66     }
67 }
68 
69 
70 class Consumer implements Runnable{
71     SyncStack stack;    
72     public Consumer(SyncStack s){
73         stack = s;
74     }
75     public void run(){
76         for(int i=0;i<20;i++){
77             char c = stack.pop();
78             System.out.println("消費:"+c);
79             try{                                       
80                 Thread.sleep((int)(Math.random()*1000));
81             }catch(InterruptedException e){
82             }
83         }
84     }
85 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM