2011-02-03 19 views
2

javaのスケジューラーをシミュレートしたい。私は3つのスレッドが定義されています。スレッド1を実行して10%、スレッド2を30%、スレッド3を残りの60%の時間を実行します。実行時間を制限するJavaのスレッドのサンプル

すべての3つのスレッドは、決して終了しない連続的な監視タスクです。

つまり、プログラムを100分間実行すると、スレッド1は10分間、スレッド2は30分間&スレッド3が60分間実行されます。

ともスレッドがシフトされるたびに(つまり、状態を実行しているに入る別のスレッド)、私は「スレッドがY秒間実行X」という

を印刷する必要がありますいずれかで上記のシミュレーションを実現する上でいくつかのポインタを提供していただけますjava。

答えて

2

このlinkはinterrestingする必要があります。

import java.util.concurrent.ScheduledThreadPoolExecutor; 
import java.util.concurrent.TimeUnit; 
public class MainThread 
{ 
     public static void main(String[] args) 
     { 
       int corePoolSize = 2; 
       ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(corePoolSize); 

       /* 
       * This will execute the WorkerThread immediately 
       */ 
       stpe.execute(new WorkerThread("WorkerThread-Running-Immediately")); 

       /* 
       * This will execute the WorkerThread only once after 10 Seconds 
       */ 
       stpe.schedule(new WorkerThread("WorkerThread-Scheduled-After-10-seconds"), 10, TimeUnit.SECONDS); 

       /* 
       * This will execute the WorkerThread continuously for every 5 seconds with an initial delay of 10 
       * seconds for the first WorkerThread to start execution cycle. In this case, whether the first 
       * WorkerThread is completed or not, the second WorkerThread will start exactly after 5 seconds hence 
       * called schedule at fixed rate. This continues till 'n' threads are executed. 
       */ 
       stpe.scheduleAtFixedRate(new WorkerThread("WorkerThread-Running-At-Fixed-Rate"), 10, 5, TimeUnit.SECONDS); 

       /* 
       * This will execute the WorkerThread continuously with an initial delay of 10 seconds for the first 
       * WorkerThread to start execution cycle. Once the first thread execution completes then a delay of 5 
       * Seconds is introduced so that the next WorkerThread execution cycle starts. This continues till 
       * 'n' thread are executed. This is called schedule each thread with a fixed delay. 
       */ 
       stpe.scheduleWithFixedDelay(new WorkerThread("WorkerThread-Running-With-Fixed-Delay"), 10, 5, TimeUnit.SECONDS); 
     } 
} 

そしてワーカースレッド:

public class WorkerThread implements Runnable 
{ 
     private String threadName  = null; 

     public WorkerThread(String threadName) 
     { 
       this.threadName = threadName; 
     } 

     public void run() 
     { 
       System.out.println(this.threadName + " started..."); 
       try 
       { 
         Thread.sleep(5000); 
       } 
       catch (InterruptedException e) 
       { 
         e.printStackTrace(); 
       } 
       System.out.println(this.threadName + " ended..."); 
     } 
} 
+0

感謝。これは私の最初の質問に完全に答えました。また、シフトする前に各スレッドが費やした時間を正確に計算できるコールバックメソッド(または他の方法)もあります。 – Harish

関連する問題