您的位置:首页 > 编程语言

代码块与函数的同步

2016-03-31 13:39 405 查看
先看下面代码:

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)即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: