本帖最后由 lcjasas 于 2013-4-3 19:03 编辑
class Ticket implements Runnable
{
private int tick = 100;
Object obj = new Object();
public void run(){
while(true){
synchronized(obj){
if(tick>0){
try { Thread.sleep(10); } catch (Exception e){}
System.out.println(Thread.currentThread().getName()+"-----sale: "+tick--);
}
}
}
}
}
class TicketDemo2
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);//创建了一个线程
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
疑问。。。
try { Thread.sleep(10); } catch (Exception e){}
这样的结果是多个线程抢夺执行权,谁抢到执行谁。
try { Thread.sleep(10); } catch (Exception e){} ;
多了一个封号,也能编译成功,但是似乎只开启了最先抢到执行权的线程,为什么啊。 |