简单处理的话,用一个静态int变量,每个线程结束给int加个1 后面: while(i!=10){ //do nothing but wait } System.out.println("所的线程执行完!");
创建线程后,可以通过isAlive()方法判断线程的状态。 Thread t = new Thread(new A()); t.start();if(!t.isAlive()) { print(); }
楼上的 我试过join的 不过好像不太行啊。。
在for循环最后加个if(i==9)system.out.print("所的线程执行完!");
这样试试 for (int i=0;i<10;i++) { Thread t = new Thread(new a()); t.start(); t.join(); //new Thread(new a()).start(); }System.out.println("所的线程执行完!");
我是想让十个线程同时运行 等十个线程全运行完了后再执行最后的print语句 Thread t = new Thread(new a()); t.start(); t.join(); 如果这么写的话 就只会有一个线程在运行了 因为用了join main主线程就不能再循环生成另外9个线程了 只有等这个t运行完后再循环 我不想要这种效果
you can for (int i=0;i<10;i++) { //Thread t = new Thread(new a()); //t.start(); //t.join(); new Thread(new a()).start(); } Thread.sleep(3000); 让主线程睡足够久不也可以吗
aniude(重返荣耀) ============ 关键是不知道那些线程要多长时间才能完全执行完哇
刚才又试着写了写。下面这些代码好像能达到要求 请高手指点一下 看看下面的代码有没有问题? public class z { public static void main(String[] args) { z z = new z(); ThreadGroup tg = new ThreadGroup("gr"); for (int i = 1; i <= 10; i++) { Thread th = new Thread(tg, new run(i, z, tg)); th.start(); } synchronized (z) { try { z.wait(); } catch (Exception ex) { ex.printStackTrace(); } } System.out.println("main退出"); }} class run implements Runnable { private int index; private z z; private ThreadGroup tg; public run(int index, z z, ThreadGroup tg) { this.index = index; this.z = z; this.tg = tg; } public void run() { try { Thread.sleep(2000); System.out.println(index + "号线程执行完"); if (tg.activeCount() <= 1) { synchronized (z) { z.notify(); } } else { System.out.println("活动线程多于1个"); } } catch (Exception ex) { ex.printStackTrace(); } } }
后面:
while(i!=10){
//do nothing but wait
}
System.out.println("所的线程执行完!");
Thread t = new Thread(new A());
t.start();if(!t.isAlive())
{
print();
}
for (int i=0;i<10;i++)
{
Thread t = new Thread(new a());
t.start();
t.join();
//new Thread(new a()).start();
}System.out.println("所的线程执行完!");
Thread t = new Thread(new a());
t.start();
t.join();
如果这么写的话 就只会有一个线程在运行了 因为用了join main主线程就不能再循环生成另外9个线程了 只有等这个t运行完后再循环
我不想要这种效果
for (int i=0;i<10;i++)
{
//Thread t = new Thread(new a());
//t.start();
//t.join();
new Thread(new a()).start();
}
Thread.sleep(3000);
让主线程睡足够久不也可以吗
============
关键是不知道那些线程要多长时间才能完全执行完哇
public class z { public static void main(String[] args) {
z z = new z();
ThreadGroup tg = new ThreadGroup("gr"); for (int i = 1; i <= 10; i++) {
Thread th = new Thread(tg, new run(i, z, tg));
th.start();
} synchronized (z) {
try {
z.wait();
} catch (Exception ex) {
ex.printStackTrace();
}
} System.out.println("main退出");
}}
class run implements Runnable {
private int index;
private z z;
private ThreadGroup tg;
public run(int index, z z, ThreadGroup tg) {
this.index = index;
this.z = z;
this.tg = tg;
} public void run() {
try {
Thread.sleep(2000);
System.out.println(index + "号线程执行完");
if (tg.activeCount() <= 1) {
synchronized (z) {
z.notify();
}
} else {
System.out.println("活动线程多于1个");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}