同步代码块

package com.cavaness.quartzbook.chapter3;

/**
 * 四个线程在卖100张票
 * @author Kevin
 *
 */
public class Test {
	public static void main(String[] args) {
		TestThread testThread = new TestThread();
		new Thread(testThread).start();
		new Thread(testThread).start();
		new Thread(testThread).start();
		new Thread(testThread).start();
	}
}
package com.cavaness.quartzbook.chapter3;

public class TestThread implements Runnable {
	private static int tickets = 100; // 一百张车票
	
	/**
	 * tickets是多个线程共享的数据,因此存在线程安全的问题。
	 */
	@Override
	public void run() {
		
		String flag = "";
		// 照理说,多个线程如果要达到同步的效果,就必须使用同一个监视对象,每个线程都会执行run方法,都会创建一个新的
	        // string对象,这就不能保证同步了,但是String类有个特点,当内容一样(都是空字符串)的时候,不会创建新的对象,所以                                                                                                                           // 是能够保持同步,如果换成String flag = new String();
               // 那就不能保证同步了,所以规范的写法是,把监视对象放在run方法之外定义,避免产生多个监视对象
		while (true) {
			synchronized (flag) {
				if (tickets > 0) {
					
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
					System.out.println("Method run:" + Thread.currentThread().getName() + 
							" is saling " + tickets--);
				}
			}
		}
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值