如果把下面的改成十个线程并发运行不同的for语句,,就我最下面写好的那个方法,参数用定义好的数组里面的十个int变量,请问要怎么写?
public static void main(String[] args) {
for(Thread t:getThreads()){
t.start();
}
}
public static Thread[] getThreads(){
Thread[] thread = new Thread[10];
for(int i=0;i<10;i++){
final Integer num = new Integer(i);
thread[i] = new Thread(new Runnable(){
public void run() {
int j=5;
while(j-->0){
System.out.println("this is thread"+num);
}
}
});
}
return thread;
}
public static void bbq(int a){
for(int b=a;b<a+2;b++){
System.out.println("for循环"+"起始值为"+a+"终止值为"+(a+2));
}
}
for(Thread t:getThreads()){
t.start();
}
因为线程执行时间太短了,用循环模拟不出效果来。
改成下面的方式
Thread[] thread =getThreads() ;
thread[0].start();
thread[1].start();
thread[2].start();
thread[3].start();
thread[4].start();
public class MyThread extends Thread{
private int num = 0;
public MyThread(Integer num){
this.num = num;
}
public void run(){
bbq(num);
}
public static MyThread[] getThreads(){
MyThread[] thread = new MyThread[10];
for(int i=0;i<10;i++){
thread[i] = new MyThread(i);
}
return thread;
}
public static void bbq(int a){
for(int b=a;b<a+2;b++){
System.out.println("for循环"+"起始值为"+a+"终止值为"+(a+2));
}
}
public static void main(String[] args) {
for(Thread t:getThreads()){
t.start();
}
}
}