- <p> </p><p>class Ticketf implements Runnable{
- private int tick=100;
- Object obj=new Object();
- public void run() {
- while(true){
- synchronized(obj){
- if(tick>0){
- try{
- Thread.sleep(12);
- }
- catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+". ..sale"+tick--);
- }
- }
- }
- }
- }</p><p>public class TickeDemof {
- public static void main(String[] args) {
- Ticketf t=new Ticketf();
- Thread t1=new Thread(t,"-001窗口");
- Thread t2=new Thread(t,"-002窗口");
- Thread t3=new Thread(t,"-003窗口");
- Thread t4=new Thread(t,"-004窗口");
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }</p><p> </p><p>
- </p><p> </p>
复制代码 大家有没有看出来这个代码哪儿出错了?对,就是因为不是同一个锁所以才出错了。把创建Object的对象这句放在成员位置上即可。
|
|