改错:关于线程

来源:百度知道 编辑:UC知道 时间:2024/06/05 12:00:55
要求在尽量少的改动程序的情况下使程序结果呈aaa与bbb交替出现,并且末尾的数字连贯
class TicketsSystem
{
public static void main(String[] args)
{
SellThread st=new SellThread();

new Thread(st).start();
try
{
Thread.sleep(1);
}
catch(Exception e)
{
e.printStackTrace();
}
st.b=true;
new Thread(st).start();

}
}

class SellThread implements Runnable
{
int tickets=100;
Object obj=new Object();
boolean b=false;
public void run()
{
if(b==false)
{
while(true)
sell();
}
else
{
while(true)
{

synchronized(this)
{
try
{
Thread.sleep(10);
}
catch(Exception e)
{
e.printStackTrace();
}
if(tickets>0)
{

System.out.println("aaa:&q

我写个简单的吧!你看看原理!里面主要有个Thread.yield();
class TicketsSystem {
public static void main(String[] args) {
new SellThread();
new SellThread();

}
}

class SellThread extends Thread {
SellThread(){
this.start();
}

public void run() {
for(int i=0;i<50;i++){
System.out.println(Thread.currentThread().getName()+"----"+i);
Thread.yield();
}

}

}