天天看點

線程的相關知識、JAVA實作死鎖、生産者消費者問題

線程有五種狀态:建立、就緒、運作、阻塞、結束

isAlive:判斷線程是否活着。就緒、運作、阻塞是活着,建立、結束是死了

getPriority、setPriority:設定優先級,明顯的是,優先級高的,cpu分的時間片多一點

sleep:Thread.sleep(毫秒) 讓目前線程休眠多少毫秒

join:合并兩個線程,當執行到這個方法的時候,等目前線程執行完,再執行主線程。

yield:當某個線程正在cpu執行的時候,遇到這個方法,讓出一次目前的cpu給其他的線程使用。

Object的wait:獲得目前對象鎖的線程阻塞;

Object的notify/notifyAll:喚醒在目前對象阻塞的其他線程;

一、死鎖的java實作

package ss;

public class TestDeadLock implements Runnable{

       public int flag = 1;

       static Object o1 = new Object(),o2 = new Object();

       public void run(){

      System.out.println("flag="+flag);

      if(flag==1){

                      synchronized(o1){

                            try {

                                      Thread.sleep(500);

                            } catch (InterruptedException e) {

                                       e.printStackTrace();

                            }

                           synchronized(o2){

                                    System.out.println("1");

                            }

                       }

                 }

             if(flag==0){

                     synchronized(o2){

                              try {

                                       Thread.sleep(500);

                              } catch (InterruptedException e) {

                                       e.printStackTrace();

                              }

                              synchronized(o1){

                                   System.out.println("0");

                      }

              }

          }

       }

       public static void main(String[] args){

              TestDeadLock td1 = new TestDeadLock();

              TestDeadLock td2 = new TestDeadLock();

              td1.flag = 1;

              td2.flag = 0;

              Thread t1 = new Thread(td1);

              Thread t2 = new Thread(td2);

              t1.start();

              t2.start();

       }

}

二、生産者消費者的java實作

package ss;

public class ProducerConsumer {

    public static void main(String[] args){

    Basket basket = new Basket();

    Producer p = new Producer(basket);

    Producer p2 = new Producer(basket);

    Producer p3 = new Producer(basket);

    Consumer c = new Consumer(basket);

    Consumer c2 = new Consumer(basket);

    Consumer c3 = new Consumer(basket);

    Thread tp = new Thread(p);

    Thread tp2 = new Thread(p2);

    Thread tp3 = new Thread(p3);

    Thread tc = new Thread(c);

    Thread tc2 = new Thread(c2);

    Thread tc3 = new Thread(c3);

    tp.setName("生産者1号");

    tp2.setName("生産者2号");

    tp3.setName("生産者3号");

    tc.setName("消費者1号");

    tc2.setName("消費者2号");

    tc3.setName("消費者3号");

    tp.start();

    tp2.start();

    tp3.start();

    tc.start();

    tc2.start();

    tc3.start();

    }

}

//生産的食物

class Food{

    int id;

    public Food(int id){

        this.id = id;

    }

    public String toString(){

        return id+"";

    }

}

//裝食物的籃子,以棧的形式呈現

class Basket{

    int index = 0;//棧頂

    Food[] foods = new Food[6];//籃子裡最多裝6個饅頭

    //生産食物

    public synchronized void push(Food food){

        //如果籃子裡已經放滿,阻塞目前線程

        while(index == foods.length){

            try {

                this.wait();

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

        this.notifyAll();

        //放入籃子裡

        foods[index] = food;

        index ++;

    }

    //消費食物

    public synchronized Food pop(){

        //如果籃子裡是空的,阻塞目前線程.後面的代碼不再執行。失去對象鎖。

        while(index == 0){

            try {

                this.wait();

            } catch (InterruptedException e) {

            e.printStackTrace();

            }

        }

        //喚醒其他等待該對象的線程(無法喚醒自己,隻有别人能喚醒自己。因為目前對象已經被鎖定。喚醒隻是将其他阻塞的          線程到就緒狀态,等目前線程執行完畢,都回到同一起跑線)

       this.notifyAll();

       //從籃子裡拿出來吃

       index -- ;

       Food food = foods[index];

       return food;

    }

}

//生産者生産食物過程

class Producer implements Runnable{

    Basket basket = null;

    public Producer(Basket basket){

        this.basket = basket;

    }

    //每次生産20個食物

    public void run(){

        for(int i=1;i<=20;i++){

            Food food = new Food(i);

            basket.push(food);

            System.out.println(Thread.currentThread().getName()+"生産食物:"+food);

            //生産一個休息會兒

            try {

                Thread.sleep((int)Math.random()*100);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

         }

      }

}

//消費者消費食物過程

class Consumer implements Runnable{

    Basket basket = null;

    public Consumer(Basket basket){

        this.basket = basket;

     }

     //消費20個食物

     public void run(){

         for(int i=1;i<=20;i++){

             Food food = basket.pop();

             System.out.println(Thread.currentThread().getName()+"消費了食物:"+food);

             //消費完休息一會

             try {

                 Thread.sleep(1000);

             } catch (InterruptedException e) {

                 e.printStackTrace();

             }

         }

    }

}

繼續閱讀