其实这个就是因为运算符优先级的问题。+count--的时候因为打印的优先级比运算的优先级要高,所以是先打印,后运算,在打印过程中线程2进入,导致count的值重复,要解决也很简单将count--的优先级提升用括号括起来先运算在打印重复的现象就不容易出现了。我基本没出现过重复的。。
- class ticket implements Runnable {
- private int count = 100;
- public void run() {
- while (count > 0) {
-
- System.out.println(Thread.currentThread().getName() + "卖出票"
- + (count--));
- try {
- Thread.sleep(50);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- // count--;
- }
- }
- }
- public class ticketDemo {
- public static void main(String[] args) {
- ticket t = new ticket();
- Thread thread1 = new Thread(t, "线程1");
- Thread thread2 = new Thread(t, "线程2");
- thread1.start();
- thread2.start();
- }
- }
复制代码 |