您的位置:首页 > 编程语言 > Java开发

java线程同步实例

2015-09-03 17:44 435 查看
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++;
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: