synchronized关键字详解1

/*
t1和t2

异步编程模型:t1线程执行t1的,t2执行t2的,两个线程之间谁也不等谁
同步编程模型:t1和t2线程执行,当t1线程必须等t2线程执行结束,t1才能执行

什么时候要同步呢?为什么要引入线程同步?
1.为了数据的安全,尽管应用程序使用率降低,但为了保证数据的安全性,必须加入线程同步机制
线程同步机制使程序变成了(等同)单线程

2.什么条件下要使用线程同步?
第一:必须是多线程环境
第二:多线程环境共享同一个数据
第三:共享的数据涉及到修改操作

以下程序演示取款例子,以下程序不适用线程同步机制,多线程同时对一个
*/
public class fuck9{
public static void main(String[] args){
//创建一个公共的账户
Account act=new Account("001",5000.0);

//创建线程对同一个账户取款
processor p=new processor(act);
Thread t1=new Thread(p);
Thread t2=new Thread(p);

t1.start();
t2.start();
//如果想共享,就用参数传参
}
}


//取款线程
class processor implements Runnable{
Account act;

//constructor
processor(Account act){
this.act=act;
}

public void run(){
act.withdraw(1000.0);
System.out.println("取款1000成功,余额"+act.getbalance);
}

}


//账户
class Account{
private String actno;
private double balance;

public Account(){}
public Account(String actno,double balance){
this.actno=actno;
this.balance=balance;
}

//setter and getter
public void setactno(String actno){
this.actno=actno;
}

public void setbalance(double balance){
this.balance=balance;
}

public String getactno(){
return actno;
}

public double getbalance(){
return balance;
}

//对外提供一个取款的方法
public void withdraw(double money){
double after=balance-money;

//更新
this.setbalance(after);
}

}

/*

以下程序演示取款例子,以下程序使用同步机制保证数据的安全
*/
public class fuck9{
public static void main(String[] args){
//创建一个公共的账户
Account act=new Account("001",5000.0);

//创建线程对同一个账户取款
processor p=new processor(act);
Thread t1=new Thread(p);
Thread t2=new Thread(p);

t1.start();
t2.start();
//如果想共享,就用参数传参
}
}


//取款线程
class processor implements Runnable{
Account act;

//constructor
processor(Account act){
this.act=act;
}

public void run(){
act.withdraw(1000.0);
System.out.println("取款1000成功,余额"+act.getbalance());
}

}


//账户
class Account{
private String actno;
private double balance;

public Account(){}
public Account(String actno,double balance){
this.actno=actno;
this.balance=balance;
}

//setter and getter
public void setactno(String actno){
this.actno=actno;
}

public void setbalance(double balance){
this.balance=balance;
}

public String getactno(){
return actno;
}

public double getbalance(){
return balance;
}

//对外提供一个取款的方法
//synchronized如果添加到成员方法上,线程拿走的也是对象锁
public void withdraw(double money){//对当前账户进行取款操作

//把需要同步的代码,放到同步语句块中
/*原理:t1线程和t2线程
t1线程执行到此处,遇到synchronized关键字,就会去寻找this的对象锁
如果找到this对象锁,则进入同步语句块中执行程序,当同步语句块中的代码执行结束之前
t1线程归还this的对象锁

在t1线程执行同步语句块的过程中,如果t2线程也过来执行以下代码,也遇到
synchronized关键字,所以也去找this的对象锁,但是该对象锁被t1线程持有,
只能在此等待this对象锁的归还。
*/

synchronized(this){
double after=balance-money;

//延迟的作用:让两个取款操作之间有一些延迟
try{Thread.sleep(1000);}catch(InterruptedException e){}

//更新
this.setbalance(after);
}


}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值