有什么办法能用循环建立多个线程,然后同时启动这多个线程?我开始想用wait来实现的,可是不行。如果用sleep还不能确定时间,有可能线程还没全部建完休眠时间就到了,还可能全建立完了可是还要等待休眠时间。请各位高手帮下忙,看看应该怎么做。import java.text.SimpleDateFormat;
import java.util.Date;
public class Threads implements Runnable {
private String date = null;
int number;
int count= 1;
private SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
public Threads(){
Date de = new Date(System.currentTimeMillis()-1000*3600*24*5);
this.date = df.format(de);
}
public static void main(String[] args){
try {
Threads tt = new Threads();
tt.waitthreads();
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void waitthreads(){
Thread th[] = new Thread[10];
int i = 0;
while(i < 10){ System.out.println("开始执行[" + i + "],[" + this.date + "]");
th[i] = new Thread(new Threads(i));
synchronized(th[i]){
try {
System.out.println("i-----------"+i);
th[i].wait();
System.out.println("i======"+i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String threadName = th[i].currentThread().getName();
System.out.println("threadName:------"+threadName);
i++; }
synchronized(th){
th.notifyAll();
} }
public void run() {
for(;count <6;count++) {
System.out.println("线程 " + number + ":计数 " + count);
}
}
public Threads(int num) {
number = num;
System.out.println("创建线程 " + number);
}
}
import java.util.Date;
public class Threads implements Runnable {
private String date = null;
int number;
int count= 1;
private SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
public Threads(){
Date de = new Date(System.currentTimeMillis()-1000*3600*24*5);
this.date = df.format(de);
}
public static void main(String[] args){
try {
Threads tt = new Threads();
tt.waitthreads();
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void waitthreads(){
Thread th[] = new Thread[10];
int i = 0;
while(i < 10){ System.out.println("开始执行[" + i + "],[" + this.date + "]");
th[i] = new Thread(new Threads(i));
synchronized(th[i]){
try {
System.out.println("i-----------"+i);
th[i].wait();
System.out.println("i======"+i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String threadName = th[i].currentThread().getName();
System.out.println("threadName:------"+threadName);
i++; }
synchronized(th){
th.notifyAll();
} }
public void run() {
for(;count <6;count++) {
System.out.println("线程 " + number + ":计数 " + count);
}
}
public Threads(int num) {
number = num;
System.out.println("创建线程 " + number);
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货