论坛首页 入门技术论坛

加不加Volatile看不出有啥效果啊?

浏览 1501 次
该帖已经被评为新手帖
作者 正文
   发表时间:2008-07-21  
import java.util.concurrent.atomic.AtomicInteger;

public class VolatilePattern1 extends Thread{

	volatile boolean shutdownRequested;
	private AtomicInteger count = new AtomicInteger();

	public void shutdown() {
		shutdownRequested = true;
	}

	public void run() { 
		System.out.println("Thread:" + Thread.currentThread().getName()+" started.");
    while (!shutdownRequested) { 
        System.out.println("working ..."+count);
        count.getAndIncrement();
        try {
					Thread.sleep(50);
				} catch(InterruptedException ie) {
					ie.printStackTrace();			
				}
    }
	}
	
	public static void main(String[] args) {
		System.out.println("Thread:" + Thread.currentThread().getName()+" started.");
		VolatilePattern1 vp = new VolatilePattern1();
		vp.start();
		try {
			Thread.sleep(2000);
		} catch(InterruptedException ie) {
			ie.printStackTrace();			
		} finally {
			vp.shutdown();
		}
	}

}
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics