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();
}

} 線程

---------------------------------------------------------------------------------------------------------------------------------------------------------------------- get

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

------------------------------------------------------------------------------------------------------------------------------------------------------ im

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();
}
}
static

相關文章
相關標籤/搜索