方法同步的重要性

如果在多线程的环境下,出现了对共享变量,那么很容易产生不想得到的结果,这个时候对于改变共享变量的方法要适当的使用"同步的机制"来保证方法的正确和完整的执行,下面的程序对上面所述的内容做了简单的演示

package com.eric.concurrency;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 主要测试通过同步机制来控制偶数的生成
 * 
 * @author Eric
 * 
 */
public class EvenBySynTest {
	public static void main(String[] args) {
		ExecutorService es = Executors.newCachedThreadPool();
		for (int i = 0; i < 10000; i++) {
			// es.execute(new EvenNotSyn());
			// es.execute(new EvenBySynClass());
			es.execute(new EvenByLockClass());
		}
		System.out.println("Not Even num is" + EvenNotSyn.maps.entrySet().size());
		es.shutdown();
	}
}

// 使用Lock 作为同步机制,得到的结果都是偶数的
/*
 * Although the try-finally requires more code than using the synchronized
 * keyword, it also represents one of the advantages of explicit Lock objects.
 * If something fails using the synchronized keyword, an exception is thrown,
 * but you don’t get the chance to do any cleanup in order to maintain your
 * system in a good state. With explicit Lock objects, you can maintain proper
 * state in your system using the finally clause.
 */
class EvenByLockClass implements Runnable {
	static int	                num	 = 0;
	static Map<String, Integer>	maps	= new HashMap<String, Integer>();
	
	public void run() {
		
		even();
		if (num % 2 != 0) {
			maps.put(Thread.currentThread() + "@", num);
			// System.out.println("Thread" + Thread.currentThread().getId() +
			// " num:" + num + "not enen");
		}
	}
	
	// 锁控制同步的方法
	public synchronized void even() {
		Lock lock = new ReentrantLock();
		try {
			
			lock.lock();
			
			num++;
			num++;
		} finally {
			
			lock.unlock();
		}
		
	}
}

// 使用synchronized 作为同步机制,得到的结果都是偶数的
class EvenBySynClass implements Runnable {
	static int	                num	 = 0;
	static Map<String, Integer>	maps	= new HashMap<String, Integer>();
	
	public void run() {
		
		even();
		if (num % 2 != 0) {
			maps.put(Thread.currentThread() + "@", num);
			// System.out.println("Thread" + Thread.currentThread().getId() +
			// " num:" + num + "not enen");
		}
	}
	
	// 同步的方法
	public synchronized void even() {
		num++;
		num++;
		
	}
}

// 非同步方法的runnable,得到的结果包含非偶数
class EvenNotSyn implements Runnable {
	static int	                num	 = 0;
	static Map<String, Integer>	maps	= new HashMap<String, Integer>();
	
	public void run() {
		
		even();
		if (num % 2 != 0) {
			maps.put(Thread.currentThread() + "@", num);
			// System.out.println("Thread" + Thread.currentThread().getId() +
			// " num:" + num + "not enen");
		}
	}
	
	public void even() {
		num++;
		num++;
		
	}
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值