本文實(shí)踐來自于【Java多線程編程核心技術(shù)】一書!
同步方法容易造成死循環(huán),如——
類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();
}
}
運(yùn)行類:
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();
}
}
相關(guān)死循環(huán)分析——
線程B永遠(yuǎn)得不到執(zhí)行機(jī)會(huì)捕传,被鎖死了!