码迷,mamicode.com
首页 > 编程语言 > 详细

【好程序员特训营】Java线程同步初探

时间:2014-12-23 10:32:35      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:java   线程   同步   

对于同步,在具体的Java代码中需要完成以下两个操作:

把竞争访问的资源标识为private;

同步那些修改变量的代码,使用synchronized关键字同步方法火代码。


synchronized关键字智能标记费抽象方法,不能标记成员变量

为了演示同步方法的使用,构建了一个信用卡账户,起初信用额为100w,然后模拟透支、存款等多个操作。显然银行账户User对象是个竞争资源,而多个并发操作的是账户方法oper(int x),当然应该在此方法上加上同步,并将账户的余额设为私有变量,禁止直接访问。

以下是代码:

public class Test {

	public static void main(String args[]){
		User u=new User("张三",100);
		MyThread t1=new MyThread("线程A",u,20);
		MyThread t2=new MyThread("线程B",u,20);
		MyThread t3=new MyThread("线程C",u,20);
		MyThread t4=new MyThread("线程D",u,20);
		MyThread t5=new MyThread("线程E",u,20);
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
		
}
	
static class MyThread extends Thread{
	private User u;
	private int y=0;
	MyThread (String name,User u,int y){
		super(name);
		this.u=u;
		this.y=y;
		
	}
	public void run(){
		u.oper(y);
	}
}
static class User{
	private String code;
	private int cash;
	User (String code,int cash){
		this.code=code;
		this.cash=cash;
	}
	public String getCode(){
		return code;
	}
	public void setCode(String code){
		this.code=code;
	}
	public synchronized void oper(int x){
		try{
			Thread.sleep(10L);
			this.cash+=x;
			System.out.println(Thread.currentThread().getName()+"运行结束,增加“"
					+x+"“,当前账户余额为:"+cash);
			
		}catch(InterruptedException e){
			e.printStackTrace();
		}
	}
	public String toString(){
		return "User{"+"code="+code+",cash="+cash+"}";
	
	}
}
}

关键点就在于
public synchronized void oper(int x){
同步了这个方法,只允许一个线程进行访问,因而避免错误的出现

技术分享

代码已经验证过了,能够实现功能

【好程序员特训营】Java线程同步初探

标签:java   线程   同步   

原文地址:http://blog.csdn.net/xiaomuzi0802/article/details/42099069

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!