存在安全问题的多线程代码:
- class Ticket implements Runnable
- {
- private int tick = 100;
- //Object obj = new Object();
- public void run()
- {
- while(true)
- {
- if(tick>0)
- {
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"...sale: "+tick--);
- }
-
- }
- }
- }
- class TicketDemo2
- {
- public static void main(String[] args)
- {
- Ticket t = new Ticket();
- Thread t1 = new Thread(t);
- Thread t2 = new Thread(t);
- Thread t3 = new Thread(t);
- Thread t4 = new Thread(t);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码
编译运行结果(截取末尾的语句):Thread-2...sale: 10
Thread-1...sale: 9
Thread-3...sale: 8
Thread-0...sale: 7
Thread-2...sale: 6
Thread-1...sale: 5
Thread-3...sale: 4
Thread-0...sale: 3
Thread-2...sale: 2
Thread-1...sale: 1
Thread-3...sale: 0
Thread-2...sale: -1
Thread-0...sale: -2
使用同步代码块的方法:
- class Ticket implements Runnable
- {
- private int tick = 100;
- Object obj = new Object();
- public void run()
- {
- while(true)
- {
- synchronized(obj)
- {
- if(tick>0)
- {
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"...sale: "+tick--);
- }
- }
- }
- }
- }
- class TicketDemo2
- {
- public static void main(String[] args)
- {
- Ticket t = new Ticket();
- Thread t1 = new Thread(t);
- Thread t2 = new Thread(t);
- Thread t3 = new Thread(t);
- Thread t4 = new Thread(t);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码
编译运行结果出现了单线程的情况,虽然负数消失了。
Thread-0...sale: 10
Thread-0...sale: 9
Thread-0...sale: 8
Thread-0...sale: 7
Thread-0...sale: 6
Thread-0...sale: 5
Thread-0...sale: 4
Thread-0...sale: 3
Thread-0...sale: 2
Thread-0...sale: 1
表示非常困惑?同步代码块的方式出错了还是其他方面?
|
|