2

我正在创建一个基于在包含解决方案的群体中混合和扰动的程序Vector

所以我创建了一个for loop在用户给定的特定时间后停止的。 在循环内部,我将调用 5 个过程,我认为如果我将每个过程放在一个线程中,将使程序在同一时间产生比调用普通方法更多的解决方案。

这里 5 创建了 5 个线程,但是当我启动它们时,即使我使用Thread.stop,或Thread.suspendThread.interruptThread.destroy

这是我的代码,你能帮我出主意吗?

我插入了一个新变量:

public volatile boolean CrossOpb = true;`

这是我的代码:

Thread CrossOp = new Thread(new Runnable() {
public void run() {
   while(CrossOpb == true){
    int rdmCross2=(int) (Math.random() * allPopulation.size())  ; // Crossover 1st vector
    int rdmCross1=(int) (Math.random() * allPopulation.size())  ;
    Vector muted = new Vector();
    Vector copy = copi((Vector) allPopulation.get(rdmCross2));
    Vector callp = copi((Vector) allPopulation.get(rdmCross1));
    muted = crossover(callp, copy);
    System.out.println("cross over Between two Randoms ----------->");
    affiche_resultat(muted);
    allPopulation.add(muted);
   }
}

});

循环:

CrossOp.setDaemon(true);

int loop = 1;
long StartTime = System.currentTimeMillis() / 1000;
for (int i = 0; i < loop; ++i) { 
    loop++;
    if (timevalue < ((System.currentTimeMillis() / 1000) - StartTime)) {
        loop = 0;
     CrossOpb = false;   
    }
CrossOp.start();
}
4

3 回答 3

2

我已经回答了一个类似的问题。在那种情况下,它是 C#,但概念是相同的。

不能杀死线程。线程必须自行退出。只需在volatile boolean某处放置一个变量,并将其设置为 true/false,当您希望线程终止时,然后在线程中,将 替换while (true)while (myVariable == true/false).

无论如何,你说:

在循环内部,我将调用 5 个程序,我认为如果我将每个程序放在一个线程中,将使程序在同一时间内做出比调用普通方法更多的解决方案。

嗯,这通常是错误的。如果过程是数据相关的(它们中的每一个都依赖于前一个的结果),那么将它们放在线程上不会有任何改变。将迭代放在管道中可能更聪明,这样您就有 5 个线程执行连续迭代的步骤。我不确定遗传算法是否可行,无论如何您都必须处理一些特殊情况(例如,突变,它会改变部分计算的迭代的数量)。

于 2013-09-15T23:42:02.507 回答
1

如何在Thread特定时间内运行:

这里的基本方法是继续计算Thread已经运行了多长时间并退出并返回结果,在我们的例子中,这里是关于Thread执行多长时间的详细信息。

注意:您必须使用System.nanoTime()asSystem.currentTimeMillis()每次在方法中调用它时都会返回相同的内容。

我使用一个Random数字来计算每个的不同生命周期,Callables这样您就可以看到它们在指定的时间内没有准确执行,但它们非常接近,并且 delta 的方差非常一致,至少在我的机器上.

这里是下面代码的要点,以便于访问。

package com.stackoverflow.Q18818482;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

public class Question18818482
{
    public static Random RND;

    static
    {
        RND = new Random();
    }

    public static void main(final String[] args)
    {
        try
        {
            final ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
            final List<Future<String>> results = new ArrayList<>(10);
            for (int i = 0; i < 10; i++)
            {
                results.add(es.submit(new TimeSliceTask(RND.nextInt(10), TimeUnit.SECONDS)));
            }
            es.shutdown();
            while(!results.isEmpty())
            {
                final Iterator<Future<String>> i = results.iterator();
                while (i.hasNext())
                {
                    final Future<String> f = i.next();
                    if (f.isDone())
                    {
                        System.out.println(f.get());
                        i.remove();
                    }
                }
            }
        }
        catch (InterruptedException e)
        {
            throw new RuntimeException(e);
        }
        catch (ExecutionException e)
        {
            throw new RuntimeException(e);
        }
    }

    public static class TimeSliceTask implements Callable<String>
    {
    private final long timeToLive;
    private final long duration;


    public TimeSliceTask(final long timeToLive, final TimeUnit timeUnit)
    {
        this.timeToLive = System.nanoTime() + timeUnit.toNanos(timeToLive);
        this.duration = timeUnit.toMillis(timeToLive);
    }

    @Override
    public String call() throws Exception
    {
        while( timeToLive <= System.nanoTime() )
        {
            // simulate work here
            Thread.sleep(500);
        }
        final long end = System.nanoTime();
        return String.format("Finished Elapsed Time = %d, scheduled for %d", TimeUnit.NANOSECONDS.toMillis(timeToLive - end), this.duration );
    }
    }
}

这是一个运行输出的样子

注意:所有时间都以毫秒为单位

Finished Elapsed Time = 999, scheduled for 1000
Finished Elapsed Time = 2998, scheduled for 3000
Finished Elapsed Time = 5999, scheduled for 6000
Finished Elapsed Time = 1994, scheduled for 2000
Finished Elapsed Time = 8994, scheduled for 9000
Finished Elapsed Time = 6993, scheduled for 7000
Finished Elapsed Time = 6993, scheduled for 7000
Finished Elapsed Time = 5993, scheduled for 6000
Finished Elapsed Time = 5998, scheduled for 6000
于 2013-09-16T02:09:41.660 回答
-2

在阅读了昨晚关于线程的全部内容后,我发现我的问题的解决方案并不难。
这个想法是编辑线程内停止循环的条件,因此我们通过给它特定的运行时间来控制它,这是我的示例:

class ProcessorCordm extends Thread {
    int runningtime;
    public ProcessorCordm(int runningtime) {
        this.runningtime = runningtime;
    }
    public void run() {
        int loop = 1;
        long StartTime = System.currentTimeMillis() / 1000;
        for (int i = 0; i < loop; ++i) {
            int rdmCross2 = (int) (Math.random() * allPopulation.size()); // Crossover 1st vector
            int rdmCross1 = (int) (Math.random() * allPopulation.size());
            Vector muted = new Vector();
            Vector copy = copi((Vector) allPopulation.get(rdmCross2));
            Vector callp = copi((Vector) allPopulation.get(rdmCross1));
            muted = crossover(callp, copy);
            System.out.println("cross over Between two Randoms ----------->");
            affiche_resultat(muted);
            addsolution(muted);
            loop++;
            if (timevalue < ((System.currentTimeMillis() / 1000) - StartTime)) {
                loop = 0;
            }
        }
    }
}

所以如果我想运行我的线程10, 我只需要:

 ProcessorCoG CrossOpg = new ProcessorCoG(10);

对于我的情况,我必须同时调用许多线程为特定的TimeValue工作,所以我使用了ExecutorServiceClass :

            ProcessorCoG CrossOpg = new ProcessorCoG(timevalue);//extends Thread class
            ProcessorCordm CrossOp = new ProcessorCordm(timevalue);//extends Thread class
            ProcessorCordm CrossOp2 = new ProcessorCordm(timevalue);//extends Thread class
            MutateGb MutGb = new MutateGb(timevalue);//extends Thread class
            MutateRdm MutRdm = new MutateRdm(timevalue);//extends Thread class
            MbsRdm MbsR = new MbsRdm(timevalue);//extends Thread class
            ExecutorService executor = Executors.newFixedThreadPool(6);
            executor.submit(MutGb);
            executor.submit(MutRdm);
            executor.submit(CrossOp);
            executor.submit(CrossOp2);
            executor.submit(CrossOpg);
            executor.submit(MbsR);
于 2013-09-17T15:41:47.967 回答