示例程序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();
}
}
}