python分布式事务_线程间的通信 - 阳光宅男---关注互联网,多线程编程,分布式事务,二阶段提交 - ITeye博客...

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

这是张孝祥老师讲的视频的例子吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值