java 卖票程序的两种实现方法

class BBBB implements Runnable
{
static  int tick=100;
//String str=new String("嘻嘻");
public  synchronized  void run()
{
while(true)
{
//synchronized(str)
// {

if(tick>0)
{
System.out.printf("%s线程正在买第%d张票\n",Thread.currentThread().getName(),tick);
tick--;
}
else
{
break;
// }

}
}
}
}
class AA
{
public static void main(String[] args)
{
BBBB aa=new BBBB();
// BBBB bb=new BBBB();
Thread t1=new Thread(aa);
Thread t=new Thread(aa);
t.start();
t1.start();
}

}

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

class BBBB extends Thread
{
public static  int tick=100;
static String str=new String("嘻嘻");
public   void run()
{
while(true)
{
synchronized(str)
{

if(tick>0)
{
System.out.printf("%s线程正在买第%d张票\n",Thread.currentThread().getName(),tick);
tick--;
}
else
{
break;
}

}
}
}
}
class AA
{
public static void main(String[] args)
{
BBBB aa=new BBBB();
BBBB bb=new BBBB();
//Thread t1=new Thread(aa);
// Thread t=new Thread(aa);
aa.start();
bb.start();
}
}

------------------------------------------------------------------------------------------------------------------------------------------------------

class BBBB implements Runnable
{
    public static  int tick=100;
        static String str=new String("嘻嘻");
public    void run()
{
while(true)
{

synchronized (str)
{
if(tick>0)
{
System.out.printf("%s线程正在买第%d张票\n",Thread.currentThread().getName(),tick);
tick--;
}
else
{
break;
}

}
}
}
}
class AA
{
public static void main(String[] args)
{
BBBB aa=new BBBB();
//BBBB bb=new BBBB();
Thread t1=new Thread(aa);
Thread t=new Thread(aa);
t.start();
t1.start();
}
}

你可能感兴趣的:(java 卖票程序的两种实现方法)