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--);
}
}
}
}
}