java线程多线程同步机制(synchronized)

        java的线程一直是一个让初学者一个头疼不已的问题,反正是当初可能学习的时候比较烦躁,线程这一部分一直没有了解过他的具体概念和用处,参加工作后才学习的这一块相关的知识,呵呵,下面不多少废话了,说正题。

       提到java多线程,难免会想到同步。线程的同步是保证多线程安全访问竞争资源的一种手段。

第一:

说到同步,为什么要对多线程访问的方法限制同步?

很明显,当然是为了避免多个线程统一操作一个数据对象时,对这个数据对象造成破坏。从而造成数据的混乱。这是不允许的。


第二:

那要怎么做,才能做一次只能让一个线程进行操作,操作完后再允许其他线程依次进行操作呢?


在这里不可避免的让我们会想到synchronized关键字

说到synchronized大家要注意一点,他只能标记非抽象的方法。

 在java里面首先我们要把需要统一操作一个数据的对象资源设置为private ,限制不能直接访问。

再而就是用synchronized修饰修改变量的方法或代码


以下是我学习时写的测试代码:分为三个clss     UserSource  CreateMythread 和一个测试的主方法类SynchronizedTest



public class UserSource {
private int num; //封装操作对象
UserSource(int num){
this.num=num;
}
public int getNum() {
return num;
}

public void setNum(int num) {
this.num = num;
}

/**
*业务逻辑操作
* synchronized同步关键字,限制一次仅有一个线程对本方法进行访问(去掉后打印可以看看多线程对数据争抢操作结果)
* */
public synchronized void chengenum(int fix){
try {
this.num+=fix;
System.out.println(Thread.currentThread().getName()+"操作后"+"  操作动作: num增加"+"“"+fix+"”"+"   当前数量:"+num);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}


public class CreateMythread extends Thread {
private UserSource  us;
private int fix=0;
CreateMythread(String name,UserSource  us,int fix){
super(name);
this.us=us;
this.fix=fix;
}
public void run() { 
us.chengenum(fix); 
 } 
}


public class SynchronizedTest {
public static void main(String[] args) {
UserSource  us=new UserSource(100);
CreateMythread  a=new CreateMythread("线程1",us,30);
CreateMythread  b=new CreateMythread("线程2",us,20);
CreateMythread  c=new CreateMythread("线程3",us,-15);
a.start();
b.start();
c.start();
}
}


运行控制台打印结果如下:

线程1操作后  操作动作: num增加“30”   当前数量:130
线程2操作后  操作动作: num增加“20”   当前数量:150
线程3操作后  操作动作: num增加“-15”   当前数量:135

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值