public static void main(String[]args)
{
Runnable tt = new Thread1();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
}
}
class Thread1 implements Runnable
{
int tickets = 100;
String str = "";
public void run()
{
while(true)
{
try {
sale();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public synchronized void sale() throws IOException
{
if(tickets>0)
{
try{Thread.sleep(60);}
catch(Exception ex){}
OutputStream os=new FileOutputStream("c:\\info.txt",true);
OutputStreamWriter osw=new OutputStreamWriter(os);
BufferedWriter bufw=new BufferedWriter(osw);
osw.write((Thread.currentThread().getName()+" ticket"+tickets--).toCharArray()
);
bufw.newLine();
bufw.flush();
bufw.close();
}
}
Thread-0 ticket100
Thread-0 ticket99
Thread-0 ticket98
Thread-0 ticket97
Thread-0 ticket96
Thread-0 ticket95
Thread-3 ticket94
Thread-1 ticket93
Thread-1 ticket92
Thread-1 ticket91
Thread-1 ticket90
Thread-2 ticket89
Thread-1 ticket88
Thread-3 ticket87
Thread-0 ticket86
Thread-3 ticket85
Thread-1 ticket84
Thread-1 ticket83
Thread-1 ticket82
Thread-1 ticket81
Thread-1 ticket80
Thread-1 ticket79
Thread-1 ticket78
Thread-1 ticket77
Thread-1 ticket76
Thread-1 ticket75
Thread-1 ticket74
Thread-1 ticket73
Thread-1 ticket72
Thread-2 ticket71
Thread-2 ticket70
Thread-2 ticket69
Thread-2 ticket68
Thread-2 ticket67
Thread-2 ticket66
Thread-2 ticket65
Thread-2 ticket64
Thread-2 ticket63
Thread-2 ticket62
Thread-2 ticket61
Thread-2 ticket60
Thread-2 ticket59
Thread-1 ticket58
Thread-3 ticket57
Thread-3 ticket56
Thread-3 ticket55
Thread-3 ticket54
Thread-3 ticket53
Thread-3 ticket52
Thread-0 ticket51
Thread-0 ticket50
Thread-0 ticket49
Thread-0 ticket48
Thread-0 ticket47
Thread-0 ticket46
Thread-3 ticket45
Thread-1 ticket44
Thread-1 ticket43
Thread-1 ticket42
Thread-1 ticket41
Thread-1 ticket40
Thread-1 ticket39
Thread-1 ticket38
Thread-1 ticket37
Thread-1 ticket36
Thread-1 ticket35
Thread-1 ticket34
Thread-1 ticket33
Thread-1 ticket32
Thread-1 ticket31
Thread-1 ticket30
Thread-1 ticket29
Thread-1 ticket28
Thread-1 ticket27
Thread-1 ticket26
Thread-1 ticket25
Thread-1 ticket24
Thread-1 ticket23
Thread-1 ticket22
Thread-1 ticket21
Thread-1 ticket20
Thread-1 ticket19
Thread-1 ticket18
Thread-1 ticket17
Thread-1 ticket16
Thread-1 ticket15
Thread-1 ticket14
Thread-1 ticket13
Thread-1 ticket12
Thread-1 ticket11
Thread-1 ticket10
Thread-1 ticket9
Thread-2 ticket8
Thread-2 ticket7
Thread-2 ticket6
Thread-2 ticket5
Thread-2 ticket4
Thread-2 ticket3
Thread-2 ticket2
Thread-2 ticket1
本人完美运行! |