日期:2014-05-20  浏览次数:20710 次

for循环创建多线程
用一个for循环创建多线程,用匿名内部类
  for(int i=0;i<10;i++){
    Thread th = new Thread(new Runnable(){
      public void run(){
        System.out.println(i);// 这个值要求要打印出0、1、2、3、4、5、6、7、8、9
      } 
    })
  }
不能打印出 0、2、3、3、6、7、8、8、9、9
要怎么样保证当for循环的i等于0的时候,内部类里面打印的值是0,当for循环的i等于1的时候,内部类里面打印的值是1;

------最佳解决方案--------------------
for(int i=0;i<10;i++){
            final int f = i;//传值用。
            Thread th = new Thread(new Thread(){
              public void run(){
                System.out.println(f);//只能访问外部的final变量。
              } 
            });
            th.start();
          }
------其他解决方案--------------------
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.
}

------其他解决方案--------------------
不是很清楚你想要表达的意思,如果光是要输出结果
public class MyThread extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}

public static void main(String[] args) throws InterruptedException {
 MyThread mt = new MyThread();