JUC线程Volatile关键字
保证内存可见性,不具备互斥性,不能保证变量的原子 性。相比较synchronized 是一种较为轻量级的同步策略。
package com.yang;
public class TestVolatile {
public static void main(String[] args) {
ThreadDemo td=new ThreadDemo();
new Thread(td).start();
while (true) {
// 加同步锁
synchronized (td) {
if (td.isflag()) {
System.out.println("---------------");
break;
}
}
}
}
}
class ThreadDemo implements Runnable{
private boolean flag=false;
public boolean isflag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
flag=true;
System.out.println("flag------> "+isflag());
}
}
使用volatile关键字
package com.yang;
public class TestVolatile {
public static void main(String[] args) {
ThreadDemo td=new ThreadDemo();
new Thread(td).start();
while (true) {
// 加同步锁
if (td.isflag()) {
System.out.println("---------------");
break;
}
}
}
}
class ThreadDemo implements Runnable{
private volatile boolean flag=false;
public boolean isflag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
flag=true;
System.out.println("flag------> "+isflag());
}
}