我们都知道在java中线程的代码形式可以写为如下
new Thread(
new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
}
).start();在多线程启动之下,线程之间的运行将是随机进行切换的,通常有的时候,我们在业务需求上可能需要线程之间有序的进行切换执行,确保业务的准切性,比如银行的取票机,还有火车的售票等,在此等业务的情况下,我们要想控制线程之间的通信,需要通过同步锁来实现
比如我希望线程a执行5此后,线程b执行10次,或者反过来,如此50次。
下面我们来看代码
class Business{
private boolean bShouldSub = true;
public synchronized void sub(int i){
while (!bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=0;j<=i;j++){
System.out.println("sub thread------------------------------------------------------------"+j);
}
bShouldSub = false;
this.notify();
}
public synchronized void main(int i){
while (bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int j = 0; j <= i; j++) {
System.out.println("main thread sequence of " + j
+ " i=" + i);
}
bShouldSub = true;
this.notify();
}
}把相称要执行的业务单独抽取成一个类,确保锁的唯一性。
private boolean bShouldSub = true;是为了 线程之间进行通信。
下面我们来看线程的执行代码
final Business business = new Business();
new Thread(
new Runnable() {
@Override
public void run() {
for(int i=0;i<=50;i++){
business.sub(5);
}
}
}
).start();
for (int i = 0; i <= 50; i++) {
business.main(10);
}
}
原文地址:http://blog.csdn.net/u013704998/article/details/45279019