ITeye博客

多线程无需加锁的情形

cloudeagle_bupt · 2016-09-15 21:18 · Markdown

package prefetch;


public class ConcurrentTest {

	public int absoluteDifference = 0 ;

	public void addDifference(double val) {
		absoluteDifference += val ;
		System.out.println(Thread.currentThread().getName() + " " + val +" absoluteDifference: "+ absoluteDifference);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ConcurrentTest ct = new ConcurrentTest() ;
		for(int i = 0 ;i<5; i++ ) 
			new Thread(new Adder(ct,i)).start() ;

		try {
			Thread.currentThread().sleep(400) ;
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Final : " + ct.absoluteDifference);
	}

}

class Adder implements Runnable {
	ConcurrentTest cc ;
	int val = 0 ;
	
	public Adder(ConcurrentTest ct, int i) {
		cc = ct ;
		val = i ;
	}

	@Override
	public void run() {
		cc.addDifference(val) ;
	}
}

当线程的执行次序对结果没有影响时,加锁与否已经无所谓了 ~

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。