Java并发编程-36-原子数组

一、同步机制存在的问题

1、死锁
2、即使只有一个线程访问这个对象,仍然需要执行必须的代码来获取和释放锁

二、Compare-and-Swap-Operation

1、取得变量值,即变量的旧值

2、在一个临时变量中修改变量值,即变量的新值

3、如果上面获得的变量旧值与当前变量值相等,就用新值替换旧值。如果已有其他线程修改了这个变量的值,上面获得的变量的旧值就可能与当前变量值不同


三、原子数组

package concurrencycollection;

import java.util.concurrent.atomic.AtomicIntegerArray;

public class Incrementer implements Runnable {

	private AtomicIntegerArray atomicIntegerArray;

	public Incrementer(AtomicIntegerArray atomicIntegerArray) {
		this.atomicIntegerArray = atomicIntegerArray;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < atomicIntegerArray.length(); i++) {
			atomicIntegerArray.getAndIncrement(i);
		}
	}
}

package concurrencycollection;

import java.util.concurrent.atomic.AtomicIntegerArray;

public class Decrementer implements Runnable {
	private AtomicIntegerArray atomicIntegerArray;

	public Decrementer(AtomicIntegerArray atomicIntegerArray) {
		this.atomicIntegerArray = atomicIntegerArray;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < atomicIntegerArray.length(); i++) {
			atomicIntegerArray.getAndDecrement(i);
		}
	}
}

package concurrencycollection;

import java.util.concurrent.atomic.AtomicIntegerArray;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(1000);
		final int THREADS = 100;
		Incrementer incrementer = new Incrementer(atomicIntegerArray);
		Decrementer decrementer = new Decrementer(atomicIntegerArray);

		Thread[] threadsIncrementer = new Thread[THREADS];
		Thread[] threadsDecrementer = new Thread[THREADS];

		for (int i = 0; i < THREADS; i++) {
			threadsIncrementer[i] = new Thread(incrementer);
			threadsDecrementer[i] = new Thread(decrementer);

			threadsIncrementer[i].start();
			threadsDecrementer[i].start();
		}

		for (int i = 0; i < 100; i++) {
			try {
				threadsIncrementer[i].join();
				threadsDecrementer[i].join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		for (int i = 0; i < atomicIntegerArray.length(); i++) {
			if (atomicIntegerArray.get(i) != 0) {
				System.out.println("Vector[" + i + "] : "
						+ atomicIntegerArray.get(i));
			}
		}

		System.out.println("Main : End of the example");
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值