多线程无需加锁的情形

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) ;
	}
}


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


你可能感兴趣的:(多线程无需加锁的情形)