美文网首页
实践【Java多线程编程核心技术】系列:同步方法造成的无限等待

实践【Java多线程编程核心技术】系列:同步方法造成的无限等待

作者: CrazyLabs | 来源:发表于2016-05-25 15:48 被阅读0次

    本文实践来自于【Java多线程编程核心技术】一书!

    同步方法容易造成死循环,如——
    类Service.java:

    package service;
    public class Service {

    synchronized public void methodA(){
        System.out.println("methodA begin");
        boolean isContinueRun = true;
        while(isContinueRun){       
        }
        System.out.println("methodA end");
    }
    synchronized public void methodB() {
        System.out.println("methodB begin");
        System.out.println("methodB end");
      }
    

    }

    线程类代码如:

    package extthread;

    import service.Service;

    public class ThreadA extends Thread {

    private Service service;
    
    public ThreadA(Service service) {
        super();
        this.service = service;
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        service.methodA();
    }
    

    }

    package extthread;
    import service.Service;
    public class ThreadB extends Thread{

    private Service service;
    
    public ThreadB(Service service) {
        super();
        this.service = service;
    }
    
    /* (non-Javadoc)
     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
        // TODO Auto-generated method stub
        service.methodB();
    }
    

    }

    运行类:

    package test.run;
    import service.Service;
    import extthread.ThreadA;
    import extthread.ThreadB;

    public class Run {

    public static void main(String[] args) {
        Service service = new Service();
        ThreadA athread = new ThreadA(service);
        athread.start();
        ThreadB bthread = new ThreadB(service);
        bthread.start();
    }
    

    }

    相关死循环分析——
    线程B永远得不到执行机会,被锁死了!

    screenshot_20160525155141.png

    相关文章

      网友评论

          本文标题:实践【Java多线程编程核心技术】系列:同步方法造成的无限等待

          本文链接:https://www.haomeiwen.com/subject/gfstdttx.html