【问题标题】:two threads in parallel by only one is getting executed in java只有一个并行的两个线程在java中被执行
【发布时间】:2023-03-20 03:26:01
【问题描述】:

我正在并行运行两个线程,只有一个正在执行:

    countDown = new CountDownLatch(2); //tasks number
    tasks = new ArrayList<Callable<Object>>();    
    //tasks.add(Executors.callable(new runCode(countDown, timelineTime2)));
    tasks.add(Executors.callable(new runCode(countDown, timelineTime_sublist1,1)));
    tasks.add(Executors.callable(new runCode(countDown, timelineTime_sublist2,2)));
    executor.invokeAll(tasks);

在输出中,它以:

开头
Thread 1 running,
Thread 2 running,
Thread 1 running,
Thread 2 running,

但之后只有线程 1 运行。

runCode 的代码是:

public static class runCode implements Runnable {
    private final CountDownLatch countDown;
    private final List<Long> timelineTimeI;
    private final int v;

    runCode (CountDownLatch countDown, List<Long> timelineTimeI, int v) {
        this.countDown = countDown;
        this.timelineTimeI = timelineTimeI;
        this.v = v;
        System.out.println("Thread "+v+ " running");
    }

    public void run1 (List<Long> timelineTimeI) throws IOException, InterruptedException {
        //do work
        for (Long l : timelineTimeI) {
            //if (v==2) thread.notifyAll();
            if (nb%1000==0) {
                System.out.println("Thread "+v+ " running");
                System.out.println(nb + " / ~ 80000");
                System.out.println("Number of active threads: "+ Thread.activeCount());
                //Print CPU Usage
                //OperatingSystemMXBean opBean = ManagementFactory.getOperatingSystemMXBean();
                System.out.println("Total Usage: "+thread.getTotalUsage());
                System.out.println("CPU Usage by Server: "+(thread.getTotalUsage()-thread.getUsageByThread(Thread.currentThread()))+"%");
                System.out.println("CPU Usage by Client: "+thread.getUsageByThread(Thread.currentThread())+"%");
                totalUsage += thread.getTotalUsage();
                totalClientUsage += thread.getUsageByThread(Thread.currentThread());
                count++;
                //System.out.println("CPU Usage: "+ opBean.getSystemLoadAverage());
            }
            candidateSetSize = 0;
            counter = t.get(l).size();
            //System.out.println("Counter: "+counter+" l: "+l+" t.get(l): "+t.get(l));

    for (Rating rate : t.get(l)) {
        //System.out.println("Rate: "+rate+" "+rate.getRate()+" "+rate.getRid()+" "+rate.getUid());
        lastOnline.put(rate.getUid(), l);               
        //liked by user, so send like notification
        if (rate.getRate() > averageRating.get(rate.getUid())) {
                    peers.get(rate.getUid()).sendLikeNotification(rate.getRid());
        } else {
            //disliked by user, so send dislike notification
                    peers.get(rate.getUid()).sendDisLikeNotification(rate.getRid());
        }
        //in the test data set so when a user sends a notification, it implies that user is online
        if (l>tborne) {             
            candidateSetSize += peers.get(rate.getUid()).sendOnlineNotification(true);      
        } else {
        candidateSetSize += peers.get(rate.getUid()).sendOnlineNotification(false);
        } nb++;
    }   
    // additional online status
    for (Integer uid : userList) {
        // if user has been online later than slot then send online
        if (lastOnline.containsKey(uid)) {
        if(l - lastOnline.get(uid) > SLOT) {
            if (l>tborne) {             
            candidateSetSize += peers.get(uid).sendOnlineNotification(true);        
            } else {
            candidateSetSize += peers.get(uid).sendOnlineNotification(false);
            }
            if(counterAddOnline.containsKey(uid)) {
            counterAddOnline.put(uid, counterAddOnline.get(uid)+1);
            } else {
            counterAddOnline.put(uid, 1);
            }
            lastOnline.put(uid, l); 
            counter++;
        }
                }   
            }
    candidateSetSizeOverTime.add(candidateSetSize/counter);
        }
    }

    public void run() {
    try {
    run1(timelineTimeI);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    countDown.countDown();
    System.out.println("Thread "+v+" finished");
    }
}

【问题讨论】:

  • 在提出这样的问题时,请清除所有不相关的代码。
  • 我已经读过,但我不明白为什么在并行启动后,它只使用线程 1,然后在线程 1 的执行结束且线程 2 没有执行时结束

标签: java multithreading


【解决方案1】:
 if (nb%1000==0) :

如果上面的行不正确,如果列表的长度不是 1000 的倍数,这是可能的......下面的语句将不会执行

  System.out.println("Thread "+v+ " running"); 

此语句对所有线程执行两次,因为它在构造函数中执行并在 nb=0 时执行,这可能是您的 nb 的初始值

【讨论】:

    【解决方案2】:

    countDown.countDown() 移动到run() 的开头。然后两个线程将在大约开始。同时。第一个线程等到第二个线程倒计时。

    【讨论】:

      【解决方案3】:

      你可以尝试使用SwingWorker在后台运行另一个线程

      http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

      【讨论】:

      • 会试试这个,但我认为线程正常启动,但只有一个线程在运行,程序在执行后结束,所以线程 2 的一些步骤在启动时运行,其余的没有在全部
      • SwingWorker 被设计用于 Swing 的上下文中,而不是用于一般的多线程。
      猜你喜欢
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      • 2019-04-19
      • 2019-09-13
      • 2021-10-12
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      相关资源
      最近更新 更多