示例程序01
public class RunThread extends Thread {
//若屬性不設置爲volatile類型,那麼每個方法體在執行的時候都會將成員變量從咱棧空間copy一份到堆空間的方法體內
//在方法體內操作的是實際是這個變量的副本,而不是棧空間的裏的那個變量。
//加上了volatile變量後,那麼變量就對各個線程是可見的了
private volatile boolean isRunning=true;
private void setRunning(Boolean isRunning) {
this.isRunning = isRunning;
}
@Override
public void run() {
System.out.println("進入run方法:");
while(isRunning) {
//。。
//isRunning = false;
}
System.out.println("線程停止");
}
public static void main(String[] args) throws Exception {
RunThread rt = new RunThread();
rt.start();//分支線程阻塞式判斷是否還在執行
Thread.sleep(1000);
rt.setRunning(false);//主線程中對變量進行更改
System.out.println("isRunning 已經設置了false值");
Thread.sleep(1000);
System.out.println(rt.isRunning);
}
}
實例02
import java.util.concurrent.atomic.AtomicInteger;
/**
* volatile 關鍵字不具備sunchronized關鍵字的原子性(同步)
*
* */
public class VolatileNoAutomic extends Thread {
private static AtomicInteger count = new AtomicInteger(0);
// private static volatile int count = 0;
//每個線程加1000
public static void addCount() {
for(int i = 0; i < 1000; i++) {
// count++;
count.incrementAndGet();
}
System.out.println(count);
}
@Override
public void run() {
addCount();
}
public static void main(String[] args) {
VolatileNoAutomic[] vna = new VolatileNoAutomic[10];
for(int i = 0; i < 10; i++) {
vna[i] = new VolatileNoAutomic();
}
//10個線程
for(int i = 0; i < 10; i++) {
vna[i].start();
}
}
}
例子程序03
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class AutomicUse {
private static AtomicInteger count = new AtomicInteger(0);
/*多個atomic在一個方法內是非原子性的,需要加synchronized進行修飾, 保證4個atomic整體原子性*/
public synchronized int addCount() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
count.addAndGet(1);
count.addAndGet(2);
count.addAndGet(3);
count.addAndGet(4);
return count.get();
}
public static void main(String[] args) {
final AutomicUse use = new AutomicUse();
List<Thread> ts = new ArrayList<Thread>();
for(int i = 0; i < 100; i++) {
ts.add(new Thread(new Runnable() {
@Override
public void run() {
System.out.println(use.addCount());
}
}));
}
for(Thread t : ts){
t.start();
}
}
}