class PlayFootball implements Runnable
{
private int num=0;
Object obj=new Object();
public void run()
{
while (true)
{
synchronized(obj)
{
if(num<10)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"进球了");
num++;
}
}
}
}
}
class PlayFootballDemo
{
public static void main(String[] args)
{
PlayFootball t=new PlayFootball();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
Thread t3=new Thread(t);
Thread t4=new Thread(t);
Thread t5=new Thread(t);
t1.setName("C罗");
t2.setName("梅西");
t3.setName("罗纳尔多");
t4.setName("贝克汉姆");
t5.setName("齐达内");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
以上是多线程,为什么一直输出的都是C罗进球了?这是一个死循环,为什么窗口只有十行?
|