不使用java中的join()一个接一个地启动线程

时间:2017-05-25 19:33:24

标签: java android multithreading threadpool java-threads

我刚接触java中的线程我有一点想法,我可以说我有10个线程,我就像这样逐个启动它

public class BaseRunnable implements Runnable {
    String ThreadNo;
    public  BaseRunnable(String ThreadNo) {
        // TODO Auto-generated constructor stub
        this.ThreadNo=ThreadNo;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub

        for(int i=0;i<50;i++)
        {
             System.out.println("Thread no "+ThreadNo+"  Running with index > "+i);
        }
    }
}

主要是Methord

BaseRunnable runnable=new BaseRunnable("1");//run on main thread
BaseRunnable runnableTwo=new BaseRunnable("2");//run on main thread
BaseRunnable runnable3=new BaseRunnable("3");//run on main thread
BaseRunnable runnable4=new BaseRunnable("4");//run on main thread
BaseRunnable runnabl5=new BaseRunnable("5");//run on main thread
BaseRunnable runnable6=new BaseRunnable("6");//run on main thread
BaseRunnable runnable7=new BaseRunnable("7");//run on main thread
BaseRunnable runnable8=new BaseRunnable("8");//run on main thread


Thread one=new Thread(runnable);
Thread two=new Thread(runnableTwo);
Thread thr3=new Thread(runnable3);
Thread thr4=new Thread(runnable4);
Thread thr5=new Thread(runnabl5);
Thread thr6=new Thread(runnable6);
Thread thr7=new Thread(runnable7);
Thread thr8=new Thread(runnable8);

one.start();
two.start();
thr3.start();
thr4.start();
thr5.start();
thr6.start();
thr7.start();
thr8.start();

我知道如果我使用join()我可以逐一运行(one.start(); one.join();)

我尝试使用synchronized的另一种方式,一个接一个地运行一个线程,但它没有按顺序排列,所以任何专家都帮助我激活它,如线程1,线程2等没有join()

请将此视为初学者的问题,请帮助

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式实现目标:

        List<BaseRunnable> list = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            list.add(new BaseRunnable(Integer.toString(i)));
        }

        for (BaseRunnable baseRunnable : list) {
            Thread thread = new Thread(baseRunnable);
            thread.start();
            while (thread.isAlive()) {
                Thread.sleep(10);
            }
        }