日期:2014-05-20 浏览次数:20951 次
for(int i=0;i<10;i++){
final int f = i;
Thread th = new Thread(new Thread(){
public void run(){
System.out.println(f);// 这个值要求要打印出0、1、2、3、4、5、6、7、8、9
}
});
th.start();
}
public class RotateThread
{
static int toBeOutput=0; //是否是要显示的线程计数。
static Object o=new Object(); //同步对象锁
public static void main(String[] args)
{
for(int i=0;i<10;i++)
{
final int j=i; //内部类只能接收final 类型。
Thread th = new Thread(new Runnable()
{
public void run()
{
synchronized(o)
{
while(j!=toBeOutput)//不是应该输出线程,就等待。
{
try
{
o.wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}//end while.
System.out.println(j);
toBeOutput++;
o.notifyAll(); //唤醒等待的线程。
}//end synchronized.
}//end run.
});//end new Thread.
th.start();
}//end for.
}//end main.
}