一,问题描述
假设有两个线程在并发运行,一个线程执行的代码中含有一个死循环如:while(true)....当该线程在执行while(true)中代码时,另一个线程会有机会执行吗?
二,示例代码(代码来源于互联网)
public class Service {
Object object1 = new Object(); public void methodA() {
synchronized (object1) {
System.out.println("methodA begin");
boolean isContinueRun = true;
//在这里执行一个死循环
while (isContinueRun) { }
System.out.println("methodA end");
}
} Object object2 = new Object(); public void methodB() {
synchronized (object2) {
System.out.println("methodB begin");
System.out.println("methodB end");
}
}
}
两个线程类的实现如下:
import service.Service; public class ThreadA extends Thread { private Service service; public ThreadA(Service service) {
super();
this.service = service;
} @Override
public void run() {
service.methodA();
} }
线程A执行methodA(),methodA()中有一个死循环
import service.Service; public class ThreadB extends Thread { private Service service; public ThreadB(Service service) {
super();
this.service = service;
} @Override
public void run() {
service.methodB();
} }
线程B执行methodB(),当线程A进入methodA()中的while死循环时,线程B的能不能执行完成?
测试类
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();
} }
执行结果:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAA4cAAAB+CAIAAAAY+vONAAAgAElEQVR4nO2d/XMbx32H73/pTNuJ67EndVqT9mSSkEqazKTJdJombZNMJhNDYWxRcjxOnUycJlM3cRvHZPRCKY78VsuSCJAEwReAEEmR1LssU6QkkiIFSwRFSnwnwXdSEo3+cABu3+8OuMML8XnmOyPxbm9vd++w99zuHaCN3PpEj8HB4WvXBnp7r128eKW7+1xf37VDNYdmZmbiScbur6ci2PGxvnAzp8zTLNhkHgAAAAAA5AdaQVvpIgAAAAAA2BGkaaUpMc2tlS5lRgwAAAAAAOQHhW2lM5kxDQAAAAAA8oP0rZScxwcAAAAAACATMrJSXUzhpgAAAAAAIEMytVLSTREIBAKBQCAQiPTCGStFIBAIBAKBQMji4dNP75hwr5VgpQgEAoFAIBDuRs5VElaKQCAQCA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lJrM4Ft9B19ZI3WZ1aUCAAAAAChCsmWlyTXKd4uor/Dkvq+UzodbIHpWlV7pCRpfJCoskO3v6pfWyLTMilIBAAAAABQh/w8sYT+RfemPFgAAAABJRU5ErkJggg==" alt="" />
由于线程A和线程B获得的对象锁不是同一把锁,从结果中可以看出,线程B是可以执行完成的。而线程A由于进入了while死循环,故线程A一直执行运行下去了(整个程序未结束),但线程B会结束。
也就是说,尽管线程A一直在while中执行,需要占用CPU。但是,线程的调度是由JVM或者说是操作系统来负责的,并不是说线程A一直在while循环,然后线程B就占用不到CPU了。对于线程A而言,它就相当于一个“计算密集型”作业了。如果我们的while循环是不断地测试某个条件是否成立,那么这种方式就很浪费CPU,可参考一个具体的实例:JAVA多线程之线程间的通信方式 中的“线程间的通信方式”第二点while轮询。
如果把Service.java修改成如下:
public class Service {
// Object object1 = new Object(); public void methodA() {
synchronized (this) {
System.out.println("methodA begin");
boolean isContinueRun = true;
//在这里执行一个死循环
while (isContinueRun) { }
System.out.println("methodA end");
}
} // Object object2 = new Object(); public void methodB() {
synchronized (this) {
System.out.println("methodB begin");
System.out.println("methodB end");
}
}
}
若线程A先获得对象锁时,由于while循环,线程A一直在while空循环中。而线程B也因为无法获得锁而执行不了methodB()。
可以看出,如果在一个线程在synchronized方法中无法退出,无法将锁释放,另一个线程就只能无限等待了。