- public class DeadLockDemo {
- public static void main(String[] args) {
- Ticket3 ticket = new Ticket3();
- Thread t1 = new Thread(ticket);
- Thread t2 = new Thread(ticket);
- t1.start();
- try{Thread.sleep(10);}catch(Exception e){}
- ticket.flag = true;
- t2.start();
- }
- }
- class Ticket3 implements Runnable {
- private int ticket = 100;
- public boolean flag = false;
- Object obj = new Object();
- @Override
- public void run() {
- if (flag) {
- while (true) {
- synchronized (obj) {
- show();
- }
- }
- } else {
- while (true) {
- show();
- }
- }
- }
- private synchronized void show() {
- synchronized (obj) {
- if(ticket>0){
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName() + "..."
- + ticket--);
- }
- }
- }
- }
复制代码
经过测试,使用this或者是类名.class,都不会发生死锁现象,求解释。 |