java 线程 变量 同步,Java:线程之间的变量同步

I'm trying to start/stop Java threads in the following way.

public class ThreadTester {

public static void main(String[] args) {

MyThread mt;

int max = 3;

for (int i = 0; i < max; i++) {

mt = new MyThread();

mt.start();

mt.finish();

}

}

}

public class MyThread extends Thread {

private volatile boolean active;

public void run() {

this.active = true;

while (isActive()) {

System.out.println("do something");

}

}

public void finish() {

this.active = false;

}

public boolean isActive() {

return active;

}

}

Everything works as expected only if max <= 2. Otherwise some threads continue with their output, although isActive should return false. That was at least my expectation.

The question: what is the proper way to synchronize a variable between the "master" and it's "slave" threads?

解决方案

You should initialize active to true during declaration and NOT in a run method.

public class MyThread extends Thread {

private volatile boolean active = true;

public void run() {

// this.active = true;

while (isActive()) {

// do nothing

}

}

public void finish() {

this.active = false;

}

}

The way you are doing it there is a race condition.

Also, the better approach for safely stopping a thread is to use interruption.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值