本帖最后由 孙百鑫 于 2013-6-27 07:42 编辑
public class Test {
public static void main(String[] args) {
ThreadDemo tm = new ThreadDemo();
Thread td1 = new Thread(tm);
Thread td2 = new Thread(tm);
td1.start();
td2.start();
}
}
public class ThreadDemo implements Runnable {
public int ticket = 100;
Object obj = new Object();
public void run() {
synchronized (obj) {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ticket > 0) {
System.out.println(Thread.currentThread().getName()
+ "+++++++" + ticket);
ticket--;
}
}
}
}
}
为什么我加了锁之后就一直是一个线程在运行,另一个线程不运行?哪里出错了?求帮忙 |