哲學(xué)家問題——CVTE

題目大意:

  • 哲學(xué)家問題,每一個都有自己的筷子,同時需要獲取別人的筷子吃飯:
    • 1.獲得筷子,吃飯1秒,然后趕緊放下筷子,思考3秒。
    • 2.否則思考。

編碼實現(xiàn)

  • 利用靜態(tài)數(shù)組統(tǒng)一保存筷子,每個人的id和其中一個筷子綁定。沒有自己的筷子,就不吃飯,哼(¬︿??¬☆)。
  • synchroinized(class),鎖定所有哲學(xué)家實例,保證線程安全。
package interview.philosopherquestion;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 哲學(xué)家問題,每一個都有自己的筷子,同時需要獲取別人的筷子吃飯:
 *  1.獲得筷子,吃飯1秒,然后趕緊放下筷子,思考3秒。
 *  2.否則思考。
 */
public class PhilosopherByMe extends Thread{
    //定義五個筷子:1表示可以使用,可以取筷子eating,0表示不可以使用,正在eating。。。
    private final static int[] ticks = {1, 1, 1, 1, 1};
    private final int id;//不可變,線程安全
    private int otherId;//只會在同步塊中修改,線程安全

    /**
     * 每一個哲學(xué)家對應(yīng)一個筷子
     * @param id
     */
    PhilosopherByMe(int id){
        this.id = id;
    }

    public void eating(){
        //鎖住所有對象實例
        synchronized (PhilosopherByMe.class){
            if(ticks[id] == 1){
                for(int i = 0; i < 5; ++i){
                    if(i != id){
                        //可以獲得另外的筷子,eating?。。?                        if (ticks[i] == 1){
                            otherId = i;
                            ticks[i] = 0;
                            ticks[id] = 0;
                            //拿到銬子后,吃飯一秒。保持占有筷子,不能被其他sb拿走
                            System.out.println("哲學(xué)家" + id + "正在拿著" + id + " 和 " + otherId +" 號筷子吃飯?。。?);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            //吃完飯,溜了溜了。
                            return;
                        }
                    }
                }
            }
        }
    }

    public void thinking(){
        synchronized (PhilosopherByMe.class){
            //放下自己的筷子和其他人的筷子
            if (ticks[id] == 0 && ticks[otherId] == 0){
                ticks[id] = 1;
                ticks[otherId] = 1;
            }
        }

        //放下筷子后,思考3秒
        System.out.println("哲學(xué)家" + id + "正在思考");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            eating();
            thinking();
        }
    }

    public static void main(String[] args) {
        //5個哲學(xué)家,5個筷子
        ExecutorService executors = Executors.newFixedThreadPool(5);
        for(int i = 0; i < 5; ++i){
            executors.submit(new PhilosopherByMe(i));
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容