限制java中线程的执行时间样本

时间:2011-02-03 08:07:25

标签: java multithreading scheduling

我想在java中模拟调度程序。我定义了三个线程。现在我想执行线程1占用10%的时间,线程2占用30%,线程3占用剩余60%的时间。

所有三个线程都是连续监视任务,永远不会结束。

即。如果我执行程序100分钟,则线程1执行10分钟,线程2执行30分钟&线程3 60分钟。

并且每当线程被移位时(即另一个线程进入运行状态),我应该打印“线程x执行Y秒”

任何人都可以提供一些关于在java中实现上述模拟的指示。

1 个答案:

答案 0 :(得分:2)

link应该是有趣的。

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...");
        }
}