同步代码块的锁为任意锁,而同步方法的锁为this,如何证明同步方法的锁为this....

package com.homework;
//同步代码块的锁为任意锁,而同步方法的锁为this,如何证明同步方法的锁为this.
/*
* 思路:创建2个线程,需要对同一资源进行操作。一个线程进入同步代码块,另外一个线程进入同步方法。
* 将同步代码块的锁定义为this,如果这样操作能保证数据的安全问题。说明这2个线程用的是同一把锁。
* 用同步来保证操作同一资源的多条语句在同一时刻只能被一个线程使用。
线程要执行同步里的语句,必须满足2个条件:1:获得cpu的执行权,2:获得同步锁。
* 
*/
public class MyRunnable2 implements Runnable{
public int sum = 0;
public boolean flag = true;
public Object obj = new Object();
@Override
public void run() {
if (flag) {//先让一个线程进入到if.
//flag = false;也可以在这里改变flag跟在测试类那里改变一样的效果
//睡眠
try {
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 3; i++) {
synchronized (this) {
sum = sum + 100;
System.out.println(Thread.currentThread().getName()
+ "存了100元,现有" + sum);
}
}
}else{// 改变flag的值。
for(int i=0;i<3;i++){
setSum();
}
}
}
public synchronized void setSum() {//同步方法的锁为this.
sum = sum + 100;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out
.println(Thread.currentThread().getName() + "存了100元,现有" + sum+":同步方法");
}
}
测试:
public class TestMyRunnable2 {
public static void main(String[] args) {
MyRunnable2 runnable = new MyRunnable2();
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
t1.start(); 
//让主线程睡眠一下。
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//改变flag的值。
runnable.flag = false;
t2.start(); 
}
}

转载于:https://my.oschina.net/u/2541146/blog/596306

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值