volatile关键字
public class VolatileTest implements Runnable{ /* * volatile 标识变量在线程间可见,不具备原子性(赋值后,可能会导致子线程逻辑出错) * * 在java中,每一个线程都自有一块工作内存区,其中存放这所有线程共享的主内存中的变量值的copy. * 当线程执行时,线程在自己的工作区域中操作这些变量。为了存取一个共享的变量,一个线程通常先获取锁定并去清除它的工作区 * 把这些共享变量从所有线程的共享内存区中正确的装入自己所在的工作内存区中, * 当线程解锁时保证该工作内存区中变量的值写回到共享内存汇中。 * * 一个线程可以执行的操作有使用(Use)、赋值(assign)、装载(load)、存储(store)、锁定(lock)、解锁(unlock) * * 主内存可以执行的操作读(Read)、写(write)、锁定(lock)、解锁(unlock),注所有操作都是原子性 * * volatile的作用就是强制线程到主内存(共享内存)中读取变量,而不是去线程工作内存中读取。从而实现了多个线程间的变量可见 * 从而实现了线程安全的可见性 */ public boolean flag = true; public static void main(String[] args) throws InterruptedException { VolatileTest test = new VolatileTest(); Thread t = new Thread(test); t.start(); Thread.sleep(3000); test.flag = false; Thread.sleep(1000); System.out.println(test.flag); } @Override public void run() { System.out.println("code is running"); boolean runFlag = false; // int i = 10; while(flag){ // while(i<0){ // i--; // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } runFlag = true; } System.out.println("stoped"); } }
Atomic类的使用
public class AtomicTest extends Thread{ public static AtomicInteger ai = new AtomicInteger(0); @Override public void run(){ for(int i =0;i<100;i++){ ai.incrementAndGet(); } System.out.println(ai); } public static void main(String[] args) { AtomicTest[] threads = new AtomicTest[10]; for(int i =0;i<threads.length;i++){ threads[i] = new AtomicTest(); } for(int i =0;i<threads.length;i++){ threads[i].start(); } } }