1、一个非long或double类型的原子变量,在没有同步的情况下,不同的线程中值是不同的,不需要特意地做同步操作。
2、如果原子变量(非long或double类型)需要在线程间保持通讯,则可以使用两种方法:
public class StopThread {//backgroundThread 线程读取不到主线程中stopRequested变量的变化
private static boolean stopRequested;
public static void main(String[] args)
throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!stopRequested)
i++;
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
}
a、使用同步的方法,如果只是要求线程间通讯,没必要这样;如果这样做了,就要求set,get都要用上同步修饰符,否则达不到效果
public class StopThread {
private static boolean stopRequested;
private static synchronized void requestStop() {//set
stopRequested = true;
}
private static synchronized boolean stopRequested() {//get
return stopRequested;
}
public static void main(String[] args)
throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!stopRequested())
i++;
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
requestStop();
}
}
b、volitile修饰符不执行互斥访问,但可以使任何线程可以读取到最新写入的值
public class StopThread {
private static volatile boolean stopRequested;
public static void main(String[] args)
throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!stopRequested)
i++;
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
}
3、尽量将可变数据限制在单个线程中