线程锁使用场景(一)

/**  
 * All rights Reserved, Designed By jakie
 * @author: jakie   
 * @date:   2018年11月11日
 * @version V1.0 
 * @Copyright: jakie. All rights reserved. 
 * 注意:仅供大家学习参考
 */
package testMQ;

/**
 * 
 * @author jakie
 *
 */
public class ThreadTest {
	/**
	 * 测试方法1
	 */
	public synchronized void test1() {

		try {
			int i = 5;
			while (i-- > 0) {
				System.out.println(Thread.currentThread().getName() + ":" + i);
				Thread.sleep(500);
			}
		} catch (Exception e) {

		}
	}

	/**
	 * 测试方法2
	 */
	public synchronized void test2() {
		try {
			int i = 5;
			while (i-- > 0) {
				System.out.println(Thread.currentThread().getName() + ":" + i);
				Thread.sleep(500);
			}
		} catch (Exception e) {

		}
	}

	public static void main(String[] args) {
		ThreadTest tt = new ThreadTest();
		//测试线程1
		Thread test1 = new Thread(new Runnable() {
			@Override
			public void run() {
				tt.test1();
			}
		}, "test1");
		//测试线程2
		Thread test2 = new Thread(new Runnable() {
			@Override
			public void run() {
				tt.test2();
			}
		}, "test2");
		test1.start();
		test2.start();
	}

}

在本例子中,两个方法都使用了synchronized,但是两个方法相当于两把锁,在main方法中是主线程是顺序执行,所以最后的执行结果如下,有0的情况是因为边界值1>0进入while循环

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值