[英]Measure the precise execution time of each thread
我有一個挑戰,我無法弄清楚。 這是場景。 我想每一秒都做一個特別的任務。 乍一看很簡單,但要點是,例如,如果運行一秒年齡的第一個線程無法在一秒內完成,例如需要超過一秒,則第二個線程必須恰好在一秒后啟動,這應該分別為 rest 個線程完成。
我嘗試使用 ManagementFactory.getThreadMXBean() 及其方法,例如 getThreadUserTime 或 getThreadCpuTime,但它們都不起作用。 現在我想知道是否真的有可能應對這一挑戰? ant有沒有可能的方法獲取Java中每個線程的真實執行時間?
謝謝
值得注意的是,不能保證每 1 秒就會運行一個新進程。 如果作業完成時間超過 1 秒,則最終會有一些備份。 如果發生這種情況,一些處理方法是:
假設一些備份是可以接受的,解決這個問題的一種方法是讓一個線程池處理工作和一個每 1 秒啟動一次新作業的管理器線程。 這樣的事情可能會起作用:
private static final Duration sleep = ofSeconds(1);
private static final Random random = new Random();
private static final ExecutorService executor = Executors.newFixedThreadPool(10);
public static void main(String args[]) throws InterruptedException
{
while(true)
{
executor.submit(new Process());
Thread.sleep(sleep.toMillis());
}
}
public static final class Process implements Runnable
{
@Override
public void run()
{
try
{
Thread.sleep(random.nextInt((int) sleep.toMillis()));
System.out.println("Done");
}
catch (InterruptedException e) { System.out.println("Stopped"); return; }
}
}
如果正在調度相同的進程,Java ScheduledExecutorService.scheduleAtFixedRate 可以為您處理進程調度: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleAtFixedRec .lang.Runnable,%20long,%20long,%20java.util.concurrent.TimeUnit)
private static final Duration sleep = ofSeconds(1);
private static final Random random = new Random();
private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
public static void main(String args[]) throws InterruptedException
{
executor.scheduleAtFixedRate(new Process(), sleep.toMillis(), sleep.toMillis(), TimeUnit.MILLISECONDS);
Thread.sleep(Duration.ofMinutes(1).toMillis());
}
public static final class Process implements Runnable
{
@Override
public void run()
{
try
{
Thread.sleep(random.nextInt((int) sleep.toMillis()));
System.out.println("Done");
}
catch (InterruptedException e) { System.out.println("Stopped"); return; }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.