代码块与函数的同步

来源:互联网 发布:mac arp 命令 编辑:程序博客网 时间:2024/05/29 06:57

先看下面代码:

class ThreadDemo1 {    public static void main(String[] args) {        TestThread tt = new TestThread();        new Thread(tt).start();        try {            Thread.sleep(1);        } catch (Exception e) {        }        tt.str = new String("method");        new Thread(tt).start();    }}class TestThread implements Runnable {    int tickets = 100;    String str = new String("");    public void run() {        if (str.equals("method")) {            while (true) {                sale();            }        } else {            while (true) {                synchronized (str) {                    if (tickets > 0) {                        try {                            Thread.sleep(10);                        } catch (Exception e) {                        }                        System.out.println(Thread.currentThread().getName()                                + " is saling ticket " + tickets--);                    }                }            }        }    }    public synchronized void sale() {        if (tickets > 0) {            try {                Thread.sleep(10);            } catch (Exception e) {            }            System.out.print("sale():");            System.out.println(Thread.currentThread().getName()                    + " is saling ticket " + tickets--);        }    }}

运行结果:
这里写图片描述

从运行结果可以看出tickets有售出0号,所以没有同步,因为线程同步块使用的是str对象的标志位,而线程同步函数使用的是this(本类)对象的标志位。所以将synchronized(str)修改为synchronized(this)即可。

1 0
原创粉丝点击