如何在线程完成可运行后停止线程?[英] How to stop a thread after it has completed the runnable?

问题描述

我有一个任务列表和有限数量的线程.目标是计算使用此线程数完成任务所需的时间.

我知道我使用线程和 Runnable 对象的方式有问题.我是他们的新手,似乎无法弄清楚如何解决它.

几秒钟后,worker.start() 行出现 java.lang.OutOfMemoryError: Java heap space error 错误.

这是我的代码:

public class Tasks {

static Timer timer; //times how long it takes to complete all tasks

public static void main(String[] args) {
    Job t1 = new Sleep(5);
    Job t2 = new Sum(1000);
    Job t3 = new Sleep(3);
    Job t4 = new Sleep(10);
    Job t5 =  new Sum(10);
    Graph g = new Graph(5);
    g.getNumEdges();
    g.addEdge(t1, t2);
    g.addEdge(t2, t3);
    g.addEdge(t2, t4);
    g.addEdge(t3, t5);
    g.addEdge(t4, t5);
    //System.out.println(t5.getPredecessor());
    System.out.println(parseGraph(g, 2));

}

public static String parseGraph(Graph graph, int K)
{
    long startTime = System.nanoTime();//start timer
    int numThreads = K;
    ArrayList<Job> x = graph.getNodes();
    //check for cycles
    CycleFinder dc = new CycleFinder(graph);
    if(dc.hasCycle()==true)
    {
        System.out.println(dc.cycle());
        return ("The graph has cycles and could not be parsed through.");
    }
    List<Thread> threads = new ArrayList<Thread>();
    ArrayList<Job> ready = new ArrayList<Job>();
    while (x.isEmpty()!= true)
    {
        for(int i=0; i<x.size(); i++)
        {
            Job y= x.get(i);
            System.out.println(y);
            if(y.getComplete()== true)
            {
                ready.remove(y);
                graph.removeNode(y);
                x.remove(y);
            }
            if(y.getPredecessor().isEmpty() || y.getPredecessor() ==null)
                ready.add(y);
        }
        for (int i = 0; i < numThreads && i < ready.size(); i++) {
            System.out.println("test");
            Runnable task = new MyRunnable(ready.get(i));
            Thread worker = new Thread(task);
            worker.setName(String.valueOf(i));
            worker.start();
            threads.add(worker);
          }
       //int running = 0;
       //do {
       //running = 0;
          //for (Thread thread : threads) {
            //if (thread.isAlive()) {
             // running++;
           // }
         // }System.out.println("We have " + running + " running threads. ");
       // } while (running > 0);
}
    long endTime = System.nanoTime();
    long duration = endTime - startTime;
    return ("The Tasks took " + (duration/1000) + " seconds");
}


}

推荐答案

你不需要..线程完成Runnable的run()方法后,应该完成了.您面临的 OOM 错误与 Runnable 的 run() 方法内部的逻辑有关.

本文地址:https://www.itbaoku.cn/post/978405.html