public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
// 子线程执行
for (int j = 0; j < 50; j++) {// 轮回50次
synchronized (TraditionalThreadCommuniction.class) {
for (int i = 0; i < 10; i++) {
System.out.println("sub thread id " + i);
}
}
}
}
}).start();
// 主线程执行
for (int j = 0; j < 50; j++) {// 轮回50次
synchronized (TraditionalThreadCommuniction.class) {
for (int i = 0; i < 100; i++) {
System.out.println("main thread id " + i);
}
}
}
}
上面这样就可以子线程和主线程就可以完成各自的循环任务了。
但是这样做并没有达到,主子线程都各自执行一次,然后轮回50次的要求。为此我们要对我们的代码进行改造。
首先我们对我们的主子线程任务进行抽象,把线程任务放到一个统一的类里,进行统一处理。
如下:
public static void main(String[] args) {
final Bisuness bisuness = new Bisuness();
new Thread(new Runnable() {
public void run() {
// 子线程执行
for (int j = 0; j < 50; j++) {// 轮回50次
bisuness.sub(j);
}
}
}).start();
// 主线程执行
for (int j = 0; j < 50; j++) {// 轮回50次
bisuness.main(j);
}
}
static class Bisuness {
public synchronized void sub(int j) {
for (int i = 0; i < 10; i++) {
System.out.println("sub thread id " + i + " loop id " + j);
}
}
public synchronized void main(int j) {
for (int i = 0; i < 100; i++) {
System.out.println("main thread id " + i + " loop id " + j);
}
}
}
这是面向对象编程的思路,把相关业务处理类放到一个class里,其他业务方法只要调方法就就可以了,做到业务对外来应用的一个透明。
当然这样做还是不够的,并没有到达两个线程间通信和相互协作的目的。
通常为了让两者之间通信,我们需要添加一个变量bSubTread=true,当子线程执行好的时候,我们让子线程停下来,并且通知主线程去执行任务,主线程跑完之后,主线程再自己停下来,通知子线程去执行。如此才能达到我们最初的目的
最后的代码就是这个样子了:
public static void main(String[] args) {
final Bisuness bisuness = new Bisuness();
new Thread(new Runnable() {
public void run() {
// 子线程执行
for (int j = 0; j < 50; j++) {// 轮回50次
bisuness.sub(j);
}
}
}).start();
// 主线程执行
for (int j = 0; j < 50; j++) {// 轮回50次
bisuness.main(j);
}
}
static class Bisuness {
boolean bSubTread = true;
public synchronized void sub(int j) {
if(!bSubTread) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 10; i++) {
System.out.println("sub thread id " + i + " loop id " + j);
}
bSubTread = false;
this.notify();
}
public synchronized void main(int j) {
if(bSubTread){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < 100; i++) {
System.out.println("main thread id " + i + " loop id " + j);
}
bSubTread = true;
this.notify();
}
}
分享到:
2014-07-06 22:38
浏览 440
评论
2 楼
xfxlch
2014-07-07
Andand 写道
这是张孝祥老师讲的视频的例子吧
1 楼
Andand
2014-07-06
这是张孝祥老师讲的视频的例子吧