我用线程失去了理智

时间:2016-03-07 06:25:21

标签: 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);
        }
    }
}

...处于SEPARATE线程中;但我不需要方法run();但是当我尝试这样做时:

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

但是,我在运行时看到的唯一线程是main()。 那么,我怎样才能使它成为单独的线程?

3 个答案:

答案 0 :(得分:5)

我发现你对线程如何运作有一个问题。

创建线程时,它会查找方法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());
       }
}

OUPUTS:

  • 线程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()保留在堆上。这种方法是进一步维持流程的方法。

答案 1 :(得分:0)

当你调用Thread.start()时,新的Thread将通过执行run()方法开始,你应该在run()方法完成run()方法之后编写线程必须做的事情然后它终止,因此它不再运行或可见。

当你有空的run()方法时,它会立即完成,因为它无关紧要。 线程应该做什么,应该调用什么?只需将该调用放入run()方法。

试试这个,也许它会像你期望的那样工作,但我只是猜测你想把你在构造函数中处理的东西移动到一个线程中。

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


public Chromosome(double[] candidate)
{        
    super();
    this.candidate=candidate;

}
//De-fault
public Chromosome()
{
    super();

}

/**
 * IMPLEMENTED
 */
public void run()
{
    if (candidate!=null) {
        //encode candidate PER parameter; using Matrix as storage
        chromosome = encode(candidate);
        chromoGen = new Random();
    } else {

        chromoGen = new Random();

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


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);
    }
}
}

答案 2 :(得分:0)

我认为你的主题很好并且必须正常工作,但是你的run方法是空的并且线程在没有你注意到的情况下被终止

试试这个:

public void run()
{
    System.out.println("I hope leaving it empty works...");
}

如果你在console中看到消息,那么一切都很好,你只需要在run方法中添加一个条件/循环/逻辑,这样就不会在你做之前终止已完成的工作。