java线程同步实例

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.junit.Test;

public class MyTest {
	/**
	 * 开启两个线程来测试同步的方法
	 * 
	 * @throws Exception
	 */
	@Test
	public void testSYN() throws Exception {
		ExecutorService threadPool = Executors.newFixedThreadPool(2);
		Money money = new Money();

		MyThread myThread1 = new MyThread(money, true);
		MyThread myThread2 = new MyThread(money, true);

		Future<Boolean> future1 = threadPool.submit(myThread1);
		Future<Boolean> future2 = threadPool.submit(myThread2);

		while (!(future1.get() && future2.get())) {

		}
		// 当两个线程都执行完毕,才将线程池shutdown,并输出结果.
		threadPool.shutdown();
		System.out.println(money.count);
	}

	/**
	 * 开启两个线程来测试不同步的方法
	 * 
	 * @throws Exception
	 */
	@Test
	public void testNotSYN() throws Exception {
		ExecutorService threadPool = Executors.newFixedThreadPool(2);
		Money money = new Money();

		MyThread myThread1 = new MyThread(money, false);
		MyThread myThread2 = new MyThread(money, false);

		Future<Boolean> future1 = threadPool.submit(myThread1);
		Future<Boolean> future2 = threadPool.submit(myThread2);

		while (!(future1.get() && future2.get())) {

		}
		// 当两个线程都执行完毕,才将线程池shutdown,并输出结果.
		threadPool.shutdown();
		System.out.println(money.count);
	}
}

class MyThread implements Callable<Boolean> {
	Money money;
	/**
	 * true:使用同步方法; false:使用不同步方法
	 */
	boolean useSynMethod = false;

	public MyThread(Money money, boolean useSynMethod) {
		this.money = money;
		this.useSynMethod = useSynMethod;
	}

	@Override
	public Boolean call() throws Exception {
		// TODO Auto-generated method stub
		if (useSynMethod) {
			for (int i = 0; i < 10000; i++) {
				money.addMoneySYN();
			}
		} else {
			for (int i = 0; i < 10000; i++) {
				money.addMoneyNotSYN();
			}
		}
		// 执行完成返回true
		return true;
	}

}

class Money {
	int count = 0;

	public Money() {
		// TODO Auto-generated constructor stub
	}

	public void addMoneyNotSYN() {
		count++;
	}

	public synchronized void addMoneySYN() {
		// TODO Auto-generated method stub
		count++;
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值