java - 我对线程失去了理智

标签 java multithreading runnable

我想要这个类的对象:

public class Chromosome implements Runnable, Comparable<Chromosome> {
    private String[] chromosome;
    public double fitness;
    private Random chromoGen;

    public Chromosome(double[] candidate) {
        super();
        //encode candidate PER parameter; using Matrix as storage
        chromosome = encode(candidate);
        chromoGen = new Random();
    }

    //De-fault
    public Chromosome() {
        super();
        chromoGen = new Random();

        //de-fault genotype
        chromosome = new String[6];
    }

    /**
     * IMPLEMENTED
     */
    public void run() {
        //I hope leaving it empty works...
    }

    public int compareTo(Chromosome c) {
        return (int) (fitness - c.fitness);
    }

    /**
     * Fitness stored in chromosome!
     */
    public void setFitness(ArrayList<double[]> target) {
        fitness = FF.fitness(this, target);
    }

    public double getFitness() {
        return fitness;
    }

    /**
     * ENCODERS/DECODERS
     */
    public String[] encode(double[] solution) {
        //subtract 2^n from solution until you reach 2^-n

        /**
         * LENGTH: 51 BITS!!
         *
         * 1st BIT IS NEGATIVE/POSITIVE
         *
         * THE PRECISION IS [2^30 <-> 2^-20]!!!
         *
         * RANGE: -2.14748...*10^9 <-> 2.14748...*10^9
         */
        String[] encoded = new String[6];

        //PER PARAMETER
        for (int j = 0; (j < 6); j++) {
            encoded[j] = encode(solution[j]);
        }

        return encoded;
    }

    public String encode(double sol) {
        /**
         * THE PRECISION IS [2^30 <-> 2^-20]!!!
         */
        double temp = sol;
        String row = "";
        //NEGATIVITY CHECK
        if (temp < 0) {
            //negative
            row = "1";
        } else {
            //positive
            row = "0";
        }
        //main seq.
        for (int n = 30; (n > (-21)); n--) {
            if ((temp - Math.pow(2, n)) >= 0) {
                temp = temp - Math.pow(2, n);
                row = row + "1";
            } else {
                row = row + "0";
            }
        }
        return row;
    }

    public double decoded(int position) {
        //returns UN-ENCODED solution
        double decoded = 0.00;
        char[] encoded = (chromosome[position]).toCharArray();
        /**
         * [n?][<--int:30-->][.][<--ratio:20-->]
         */
        int n = 30;
        for (int i = 1; (i < encoded.length); i++) {
            if (encoded[i] == '1') {
                decoded += Math.pow(2, n);
            }
            //next binary-place
            n--;
        }
        //NEGATIVE??
        if (encoded[0] == '1') {
            decoded = ((-1) * decoded);
        }
        //Output
        return decoded;
    }

    /**
     * GETTERS
     * ---------------\/--REDUNDANT!!
     */
    public double getParameter(int parameter) {
        //decoded solution
        return decoded(parameter);
    }

    /**
     * Used in E-algrm.
     */
    public String getRow(int row) {
        //encoded solution
        return chromosome[row];
    }

    /**
     * SETTERS
     */
    public void setRow(String encoded, int row) {
        chromosome[row] = encoded;
    }

    public void setRow(double decoded, int row) {
        chromosome[row] = encode(decoded);
    }

    /**
     * MUTATIONS
     */
    public void mutate(double mutationRate) {
        //range of: 51
        double ran = 0;
        int r;
        char[] temp;
        for (int m = 0; (m < 6); m++) {
            temp = (chromosome[m]).toCharArray();
            ran = chromoGen.nextDouble();
            if (ran <= mutationRate) {
                r = chromoGen.nextInt(51);
                if (temp[r] == '1') {
                    temp[r] = '0';
                } else {
                    temp[r] = '1';
                }
            }
            //output
            chromosome[m] = new String(temp);
        }
    }
}

...在单独的线程中;但是我不需要方法 run();但是当我尝试这样做时:

child1 = new Chromosome();
(new Thread(child1)).start();

不过,我在运行时看到的唯一线程是 main()。 那么,我怎样才能让它成为独立的线程呢??

最佳答案

我发现您对线程工作原理的理解有问题。

当您创建一个线程时,它会查找方法run()。有几种创建线程的方法。我通过传递一个 Runnable 对象来做到这一点。

Thread t=new Thread(new Runnable);

你知道一个线程有多长吗?

  • 只要方法 run() 存在并运行,线程就会存在。线程只执行 run() 方法中的代码。它不是为执行 run() 之外的任何东西而设计的。当控件移出 run() 时线程终止。

您的案例:

您将 run() 方法留空了。因此,线程什么都不执行,并在创建时死亡。

你能做什么?

将程序的其余部分包含在 run() 中,以便 run() 保留在堆上,因此新创建的线程会运行该程序。

您不需要将所有内容都放入run(),您可以简单地将第一个方法调用转移到run(),以便它保留在堆上。

举个例子:

public class threading implements Runnable
{
     public static void main(String args[])
     {
       Thread t = new Thread (new Runnable);
        t.setName("thread1");
        t.start();
         print1();
         print2();

     }    
      public static void print2()
      {
      System.out.println(Thread.getName());
       }
       public static void print1()
      {
      System.out.println(Thread.getName());
       }
       public void run()
       {
      System.out.println(Thread.getName());
       }
}

输出:

  • 线程1
  • 主要
  • 主要

是时候让您的新话题保持活跃到最后了。

public class threading implements Runnable
{
     public static void main(String args[])
     {
       Thread t = new Thread (new Runnable);
        t.setName("thread1");
        t.start();


     }    
      public static void print2()
      {
      System.out.println(Thread.getName());
       }
       public static void print1()
      {
      System.out.println(Thread.getName());
       print2();
       }
       public void run()
       {
      System.out.println(Thread.getName());
        print1();
       }
}

输出:

  • 线程1
  • 线程1
  • 线程1

我们通过在 run() 中调用方法,将方法 run() 保留在堆上。这种方法是进一步保持流量的方法。

关于java - 我对线程失去了理智,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35837458/

相关文章:

java - 如何在 TableLayout 中将按钮相互粘贴?

java - JAVA 中的网络爬虫。 java.out.lang.outofmemory 无法创建 native 线程

c++ - C++中的静态初始化和线程安全

java - Thread为什么要实现Runnable?

android postDelayed 和 removeCallbacksAndMessages 同步

java - 如何处理过大的JDialog

java - Play-Framework - 禁用公用文件夹修改重新加载

java - 三角形绘制方法

java - 如何优化 Tomcat 上运行的 Java 进程

java - SwingUtilities/Platform .runLater 之间有什么区别?