62,628
社区成员
发帖
与我相关
我的任务
分享
public class ThreadDemo1 implements Runnable{
public static void main(String[] args) throws InterruptedException {
ThreadDemo1 t1 = new ThreadDemo1();
Thread t = new Thread(t1, "thread1");
t.start();
Thread.currentThread().sleep(10);
t1.cancel();
System.out.println("检查线程的运行状态标志flag:"+t1.flag);
System.out.println(t.getName()+" is interrupt: "+t.isInterrupted());
}
boolean flag = true;
int i=0;
@Override
public void run() {
System.out.println("thread运行状态:"+flag);
while(flag){
i++;
}
System.out.println("输出结果: i= "+i);
}
public void cancel(){
flag = false;
}
}
A write to a volatile field (§8.3.1.4) happens-before every subsequent read of that field.
也就是把12行变成
volatile boolean flag = true;
这个问题看似简单,实际上水很深。当初阿里dubbo框架开发组的leader梁飞发现即使在阿里巴巴相对精锐的团队里,也有很多兄弟对此一头雾水,他不得不开课来培训这个问题。
lz如果是初学者,可以先跳过这个问题,先记住多线程下公共属性的并发的套路,等打好了基础再回头来学习这个问题。
public class ThreadDemo1 implements Runnable{
private int counter;
private boolean flag = true;
public synchronized boolean getFlag(){
return this.flag;
}
public synchronized void increaseCounter(){
counter ++;
}
public static void main(String[] args) throws InterruptedException {
ThreadDemo1 t1 = new ThreadDemo1();
Thread t = new Thread(t1, "thread1");
t.start();
Thread.currentThread().sleep(10);
t1.cancel();
System.out.println("检查线程的运行状态标志flag:"+t1.flag);
System.out.println(t.getName()+" is interrupt: "+t.isInterrupted());
}
@Override
public void run() {
System.out.println("thread运行状态:"+flag);
while(getFlag()){
increaseCounter();
}
System.out.println("输出结果: i= "+ this.counter);
}
public synchronized void cancel(){
flag = false;
}
}