synchronized锁 很强大
    一旦对象被锁定 不释放的情况下 其他对象都要等待
    这就与可能产生一个死锁的问题
    如 线程one 想拿资源a和b 线程two 也想拿资源a和b
    但是one先拿了a two先拿了b 这时one和two都在等待对方先释放资源 这时就是死锁

    死锁的效果
    哲学家就餐问题
    四个哲学家 每个人左右手都有一根筷子 同时拿到两根才能吃饭

    如何解决死锁
    1 礼让 —-> 产生时间差 按顺序吃
    2 不要产生对象公用的问题

    筷子:

    1. public class Chopstick {
    2. private int num;
    3. public Chopstick(int num){
    4. this.num = num;
    5. }
    6. public int getNum(){
    7. return this.num;
    8. }
    9. }

    哲学家:

    1. public class Philosopher extends Thread{
    2. private String pname;//哲学家姓名
    3. private Chopstick left;//左手边的筷子
    4. private Chopstick right;//右手边的筷子
    5. private long time;//哲学家沉睡的时间 让每个人先睡一定的时间 睡的时间不同就能让程序执行
    6. public Philosopher(String pname,Chopstick left,Chopstick right,long time){
    7. this.pname = pname;
    8. this.left = left;
    9. this.right = right;
    10. this.time = time;
    11. }
    12. public void run(){
    13. try {
    14. Thread.sleep(time);
    15. } catch (InterruptedException e) {
    16. e.printStackTrace();
    17. }
    18. synchronized (left){
    19. System.out.println(this.pname+"拿起了左手边的"+this.left.getNum()+"筷子");
    20. synchronized (right){
    21. System.out.println(this.pname+"拿起了右手边的"+this.right.getNum()+"筷子");
    22. System.out.println(this.pname+"吃饭了");
    23. }
    24. }
    25. }
    26. }

    主方法:

    1. public static void main(String[] args){
    2. Chopstick c1 = new Chopstick(1);
    3. Chopstick c2 = new Chopstick(2);
    4. Chopstick c3 = new Chopstick(3);
    5. Chopstick c4 = new Chopstick(4);
    6. Philosopher p1 = new Philosopher("哲学家a",c2,c1,0);
    7. Philosopher p2 = new Philosopher("哲学家b",c3,c2,3000);
    8. Philosopher p3 = new Philosopher("哲学家c",c4,c3,0);
    9. Philosopher p4 = new Philosopher("哲学家d",c1,c4,3000);
    10. p1.start();
    11. p2.start();
    12. p3.start();
    13. p4.start();
    14. }