非静态方法的锁是实例对象本身(this),静态方法的锁是类对象本身(.class)

来源:互联网 发布:安装mysql后怎么使用 编辑:程序博客网 时间:2024/05/22 12:56
public class LockTest {    public static void main(String[] args) {        MyThread mt = new MyThread();        Thread t1 = new Thread(mt);        Thread t2 = new Thread(mt);        t1.start();        try {            Thread.sleep(10);        } catch (Exception e) {}        mt.flag = false;        t2.start();    }}class MyThread implements Runnable{    private  int num = 100;    boolean flag = true;    @Override    public void run() {        if(flag){            while(true){                synchronized(this){    //更改这里                    if(num > 0){                        try {                            Thread.sleep(10);                            System.out.println(Thread.currentThread().getName()+"__run__"+num--);                        } catch (Exception e) {}                    }                }               }        } else{            while(true){                this.show();            }        }    }    public synchronized void show(){     //还有这里        if(num > 0){            try {                Thread.sleep(10);                System.out.println(Thread.currentThread().getName()+"__show__"+num--);            } catch (Exception e) {}        }    }}
阅读全文
0 0