本帖最后由 914360849 于 2015-6-26 22:56 编辑
- //指定窗口卖指定票
- public class ThreadTest {
- public static void main(String[] args) {
-
- TicketThread t1=new TicketThread();
- TicketThread t2=new TicketThread();
- TicketThread t3=new TicketThread();
- TicketThread t4=new TicketThread();
-
- t1.setName("口1");
- t2.setName("口2");
- t3.setName("窗口3");
- t4.setName("口4");
-
- t1.start();
- t2.start();
- t3.start();
- t4.start()<div class="blockcode"><blockquote>public class TicketThread extends Thread {
- private static int ticket = 20;
- static Object obj = new Object();
- @Override
- public void run() {
- while (true) {
- synchronized (obj) {//obj换成this就没事了???
- if (ticket > 0) {
- String tname = getName();
- if (ticket == 10) {
- if (!("窗口3".equals(tname))) {
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- } else {
- System.out.println(getName() + "卖" + (ticket--)
- + "---张票。");
- notifyAll();
- continue;
- }
- }
- System.out.println(getName() + "卖" + (ticket--) + "张票。");
- }
- }
- }
- }
- }
复制代码
;
}
}synchronized()里面传入this就ok 传入TicketThread .class为啥报错 但是实现Runnable接口就正常了
|