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.
}
MyThread mt1 = new MyThread();
//你也可以改成for循环来创建线程
// mt.run();//一个线程先运行0,1,2..,0,1,2,3
// mt1.run();
mt.start();//两个线程交替0,0,1,1,2,2结果可能会不同,因为两个线程交替,会出现不同情况
mt1.start();
}
}
[其他解释]
你的需求真诡异,具体实现如下
Thread t = null;
for(int i = 0; i < 10; i++) {
final int count = i;
final Thread thread = t;
t = new Thread() {
@Override
public void run() {
System.out.println(count);
if (thread != null)
try {
thread.join();
} catch (Exception e) {
}
}
};
t.start();
}
for(int i=0;i<10;i++){
Thread th = new Thread(new Runnable(){//而且这样写也报错,可以写成new Thread(new Runnable(){,
public void run(){
System.out.println(i);// 这个i都会报错
}
})
}
假如有5个大小为50M的文件,我就要开5个线程来拷贝
[其他解释]
谢谢大家,成功解决了!