实践【Java多线程编程核心技术】系列:同步方法造成的无限等待
2016-05-25 本文已影响0人
CrazyLabs
本文实践来自于【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永远得不到执行机会,被锁死了!