求助怎么写,不太懂多线程

解决方案 »

  1.   

    参考下  https://bbs.csdn.net/topics/392276600
      

  2.   

    public class MyThread implements Runnable {
        private String name;
        private int index;
        private int length;
        public MyThread(String name,int index,int length){
            this.name=name;
            this.index=index;
            this.length=length;
        }    @Override
        public void run() {
            for (int i = this.index; i < this.index + this.length; i++) {
                System.out.println(this.name+":"+i);
            }
        }
    }public class Test {    public static void putOut(int n,int m){
            for(int i=1;i<=m;i++){
                Thread t = new Thread(new MyThread("第" + i + "个线程", (1 + (n / m) * (i - 1)), n / m));
                t.start();
                try {
                    t.join();//使用join()使线程按顺序执行
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }    public static void main(String[] args){
            putOut(20,5);
        }
    }输出结果
    第1个线程:1
    第1个线程:2
    第1个线程:3
    第1个线程:4
    第2个线程:5
    第2个线程:6
    第2个线程:7
    第2个线程:8
    第3个线程:9
    第3个线程:10
    第3个线程:11
    第3个线程:12
    第4个线程:13
    第4个线程:14
    第4个线程:15
    第4个线程:16
    第5个线程:17
    第5个线程:18
    第5个线程:19
    第5个线程:20