Java多线程与并发——死锁与中断线程

过多的同步有可能出现死锁,死锁的操作一般是在程序运行的时候才有可能出现。

多线程中要进行资源的共享,就需要同步,但同步过多,就可能造成死锁。

死锁例子:

package com.vince;
/**
 * 线程死锁
 * @author acer
 *
 */
public class DeadThreadDemo {

    
    public static void main(String[] args) {
        new DeadThread();

    }

}

//顾客
class Customer{
    public synchronized void say(Waiter w){
        System.out.println("顾客说,先吃饭在买单");
        w.doService();
    }
    public synchronized void doService(){
        System.out.println("同意了,买完单在吃饭");
    }
}

//服务生
class Waiter{
    public synchronized void say(Customer c){
        System.out.println("服务员说,先买单在吃饭");
        c.doService();
    }
    public synchronized void doService(){
        System.out.println("同意了,吃完饭在买单");
    }
}

//死锁线程
class DeadThread implements Runnable{
    Customer c=new Customer();
    Waiter w=new Waiter();
    public DeadThread(){
        new Thread(this).start();
        w.say(c);
    }
    public void run() {
        c.say(w);
        
    }
    
}

中断线程例子:

package com.vince;

/**
 * 中断线程,自定义标记
 * @author acer
 *
 */
public class ThreadDemo {


    public static void main(String[] args) {
        MyThread mt=new MyThread();
        Thread t1=new Thread(mt);
        t1.start();
        //t1.stop();//停止
        for(int i=0;i<10;i++){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
        mt.flag=false;
    }
    
    
    static class MyThread implements Runnable{
        public boolean flag;
        public MyThread(){
            flag=true;
        }
        public void run() {
            int i=0;
            while(flag){
                System.out.println("i="+i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
                i++;
                if(i==100) break;//退出循环
            }
        }
        
        
}
}
原文地址:https://www.cnblogs.com/shenhainixin/p/5143729.html