Java使用Thread和Runnable开启多线程

import geneticalgorithm.util.Util;

public class GeneticAlgorithm {

    public static void main(String[] args) throws InterruptedException {
        GeneticAlgorithm ga = new GeneticAlgorithm();


        int processors = Runtime.getRuntime().availableProcessors();
        System.out.println("CPU cores: " + processors);

        long avgtime = 0;
        for (int i = 0; i < 40; i++) {
            avgtime += ga.parallel();
        }
        avgtime /= 40;

        System.out.println(avgtime);


        avgtime = 0;
        for (int i = 0; i < 40; i++) {
            avgtime += ga.serial();
        }
        System.out.println(avgtime);
    }


    public int[][] pop1;
    public int[][] pop2;
    public int lind = 10000;
    public int nind = 100;

    public GeneticAlgorithm() {
        this.pop1 = new int[nind][lind];
        this.pop2 = new int[nind][lind];
        this.initPops();
    }

    public void initPop(int[][] pop) {
        for (int i = 0; i < pop.length; i++) {
            pop[i] = Util.randArr(lind);
//            System.out.println(Arrays.toString(pop[i]));
        }
    }

    public void initPops() {
        initPop(pop1);
        initPop(pop2);
    }

    public void mutate(int[][] pop) {
        //i从1开始 保留精英
        for (int i = 1; i < this.nind - 1; i += 2) {
            int r1 = Util.randInt(this.lind);//产生[0,20)的随机整数
            int r2 = Util.randInt(this.lind);
            int gene1 = pop[i][r1];
            int gene2 = pop[i + 1][r2];
            pop[i][r1] = gene2;
            pop[i][r2] = gene1;
        }
    }
    
    public long parallel() throws InterruptedException {
        Thread t1 = new Thread(() -> mutate(pop1), "t1");
        Thread t2 = new Thread(() -> mutate(pop2), "t2");
        t1.start();
        t2.start();
        long begin = System.nanoTime();
        t1.join(); // 确保t1执行完毕
        t2.join(); // 确保t2执行完毕
        long end = System.nanoTime();
        return end - begin;
    }

    public long serial() {
        long begin = System.nanoTime();
        mutate(pop1);
        mutate(pop2);
        long end = System.nanoTime();
        return end - begin;
    }
}

你可能感兴趣的:(java,开发语言)