本帖最后由 bluecountry 于 2011-07-21 15:51:09 编辑

解决方案 »

  1.   

    简化一下问题
    A a;
    for(2次){
     a= new A();
    }关掉的时候a.release()只关了后面那个实例.
    不用数组,怎么用a把2个都关掉
      

  2.   

    public class Test {
    private test1 t1; public static void main(String[] args) {
    Test t = new Test();
    t.logic();
    try {
    Thread.sleep(5000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    } private void logic() {
    for (int i = 0; i < 2; i++) {
    t1 = new test1();
    t1.setDaemon(true);
    t1.start();
    }
    }
    }class test1 extends Thread { @Override
    public void run() {
    while (true) {
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println(currentThread().getName());
    }
    }
    }要只是为了让这些线程在主线程结束时停止,设置成守护线程就行了
      

  3.   

    package a;import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    public class Test {
    private test1 t1;
    private int threadCount = 2;
    private ExecutorService pool = Executors.newFixedThreadPool(threadCount);
    public static void main(String[] args) {
    Test t = new Test();
    t.logic();
    try {
    Thread.sleep(5000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    } finally {
    t.endLogic();
    }
    } private void logic() {
    for (int i = 0; i < threadCount; i++) {
    t1 = new test1();
    pool.execute(t1);
    }
    }

    private void endLogic(){
    pool.shutdownNow();
    }
    }class test1 extends Thread {
    @Override
    public void run() {
    while (true) {
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    break;
    }
    System.out.println(currentThread().getName());
    }
    }
    }
    线程池呢
      

  4.   

    private static boolean flag = false;
    flag 换成静态的试下