我有一个很棘手的问题希望大侠们帮助。为了把问题说的清楚些,我贴图:
程序原来是单线程的,main thread 先执行。然后用for循环将sub thread 1-6 依次执行。然后main thread 继续执行。
在1-6 每一个method都有返回值(true and false),任何一个返回false时候,main thread 都会停止。为了提高上面的运行速度,我试图用多线程 将1-6 都用一个线程来执行。 主线程指向第一横线的位置,停止,并开6个线程。然后检查者6个线程的返回状态,如果都返回true,主线程继续执行,如果任意一个线程饭后false。主线程都会停止。希望大侠们能给我提供写解决方案

解决方案 »

  1.   

    我目前的解决方案是作一个 ThreadMgr。和 Task。task代码如下public abstract class Task implements Runnable{
    private ThreadMgr mgr;
    private String threadName;

    public Task(ThreadMgr mgr , String threadName) {
    this.mgr = mgr;
    this.threadName = threadName;
    }

    public String getThreadName() {
    return threadName;
    }

    public abstract void run();

    public void setBlock() {
    mgr.setBlock(true);
    }

    }
    task就是用来创建 sub thread 1-6 ,并将返回状态返回给 ThreadMgr 。
      

  2.   

    ThreadMgr有一个list保持着创建的6个子线程,有一个private boolean block = false,表示是否有子线程返回false。然后start这些线程。然后检查这6个子线程的状态子线程集合:
    List<Thread> threadList = new ArrayList<Thread>();启动所有的子线程public void execute() throws Exception {
    for (Thread task : threadList) {
    task.start();
    }}检查状态
    public void execute() throws Exception {
    for (Thread task : threadList) {
    task.start();
    }

    if(block) {
    return;
    }

    Thread.sleep(20);

    while (true) {

    if(block) {
    break;
    }
    if(threadList.size() == 0) {
    break;
    } Thread.sleep(1);

    Iterator<Thread> IT = threadList.iterator();
    while (IT.hasNext()) {
    Thread task = IT.next();
     //代表线程结束,从list中删除
    if (task.getState() == Thread.State.TERMINATED) {
    IT.remove();
    }
    }

    }
    }
      

  3.   

     to :qianzhimeiying
    ?那我想贴图如何办?
      

  4.   

    to :(zxczxc1231231231)
    我的心啊。凉啊。
      

  5.   

    首先,楼主要将单线程的代码,拆分成多线程的代码。
        一定要注意,单线程的代码是否可以并行处理。
        若将单一线程的代码,分六个子线程,每个都执行一遍,那就没啥意思了。
    其次,我这里采用线程池,按楼主思路编了一个代码,楼主可以参考一下。
    package houlei.csdn.java.util.concurrent;import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    /**
     *
     * @author 侯磊
     */
    public class MainThread {
        /**
         * 一个任务要分成六个线程并发处理。
         */
        private static final int nThreads = 6;
        static class SubTask implements Callable<Boolean>{
            private boolean result ;
            private static volatile java.util.Random rand = new java.util.Random(System.currentTimeMillis());
            public SubTask(boolean result){this.result=result;}
            /**
             * 六个子任务的实现内容。(六个线程,执行的内容应该不是相同的)
             */
            public Boolean call() throws Exception {
                 long delay = rand.nextInt(3000);
                 System.out.println(Thread.currentThread().getName()+" get "+result+" result and delay "+delay+" ms.");
                 Thread.sleep(delay);
                return result;
            }
        }    public static void main(String args []) throws InterruptedException, ExecutionException{
         //之前的代码放在before方法体中
            before();
            //记录核心代码的运行起止时间
            long time = System.currentTimeMillis();
            //创建六个子线程的执行代码对象
            List<Callable<Boolean>> subTasks = getTasks();
            //创建线程池,用于执行上述的代码对象
            ExecutorService pool = Executors.newFixedThreadPool(nThreads);
            //执行代码,获得Future对象,用于判断上述代码对象的执行结果
            List<Future<Boolean>> futures = pool.invokeAll(subTasks);
            //判断上述代码对象的执行结果
            boolean allTrue = awaitFutures(futures);
            //关闭线程池。(即使有没有执行完的线程,也依然关闭)
            pool.shutdownNow();
            //打印核心代码的运行时间。(该时间只是一个大概的时间)
            System.out.println("running "+(System.currentTimeMillis()-time)+" ms.");
            //之后的代码可放在after方法中。参数allTrue表示上述六个线程的执行结果,是全TRUE还是有一个FALSE。
            after(allTrue);
        }
        private static  void before(){}
        private static  void after(boolean allTure){}
        private static List<Callable<Boolean>> getTasks(){
            List<Callable<Boolean>> subTasks = new ArrayList<Callable<Boolean>>(nThreads);
            subTasks.add(new SubTask(false));
            subTasks.add(new SubTask(true));
            subTasks.add(new SubTask(true));
            subTasks.add(new SubTask(true));
            subTasks.add(new SubTask(true));
            subTasks.add(new SubTask(true));
            return subTasks;
        }
        private static boolean awaitFutures(List<Future<Boolean>> futures) throws InterruptedException, ExecutionException{
            boolean checking = true;
            while(checking){
                int count = 0;
                for(Future<Boolean> f : futures){
                    if(f.isDone()){
                        if(f.get()){
                            count++;
                        }else {
                            return false;
                        }
                    }
                }
                if(count==futures.size())return true;
                Thread.sleep(10);
            }
            return false;
        }}
      

  6.   

    to:侯磊 ,zhou02607在此拜谢侯同学的鼎力支持 与zhou的见解,我现在做的事情貌似就是单一线程的代码,分六个子线程,每个都执行一遍。
    但是我还是有一点不明白,你们所说的单线程是否有浪费时间再等待状态与单线程的代码是否可以并行处理,这指的是什么?可以理解成代码里有Thread.sleep(),才有必要进行多线程的处理吗?如果没有sleep,作多线程在速度上没有提升了.
      

  7.   

    对于密集型计算来说,CPU 最优的核心线程处理能力是:CPU核数 + 1太多的线程会导致 CPU 频繁地进行线程调度,反而会降低性能。
      

  8.   

    你的问题应该在最后贴的一段代码。用sleep效率低。
    我给一段示例代码,你将就着看。    public void start() throws InterruptedException {
            final int[] arr = {0};
            int x = arr[0];
            Test[] t = new Test[6];
            synchronized (arr) {
                //synchronized 放在 for 之前保证当前线程首先获得锁。
                for (int i = 0; i < t.length; i++) {
                    t[i] = new Test(arr);
                    new Thread(t[i]).start();
                }
                while (arr[0] < t.length) {
                    arr.wait();
                    if (arr[0] == x) {
                        for (int i = 0; i < t.length; i++) {
                            t[i].stop();
                        }
                        return;
                    }
                    x = arr[0];
                }
            }
        }    private static class Test implements Runnable {        public Test(int[] arr) {
                this.arr = arr;
            }        public void run() {
                //
                boolean runResult = true;
                synchronized (arr) {
                    arr[0] += runResult ? 1 : 0;
                    arr.notify();
                }
            }        private void stop() {
            }
            private final int[] arr;
        }
      

  9.   

    看了一下API,上面的线程调度有点问题。改一下。    public void start() throws InterruptedException {
            Test[] t = new Test[6];
            final int[] arr = {0, 0};
            for (int i = 0; i < t.length; i++) {
                t[i] = new Test(arr);
                new Thread(t[i]).start();
            }
            synchronized (arr) {
                while (arr[0] < t.length) {
                    if (arr[1] > 0) {
                        for (int i = 0; i < arr.length; i++) {
                            t[i].stop();
                        }
                        return;
                    }
                    arr.wait();
                }
            }
            //
        }    private static class Test implements Runnable {        public Test(int[] arr) {
                this.arr = arr;
            }        public void run() {
                //
                boolean runResult = true;
                synchronized (arr) {
                    arr[runResult ? 0 : 1]++;
                    arr.notify();
                }
            }        private void stop() {
            }
            private final int[] arr;
        }