确定Java程序的确定性线程执行

时间:2009-08-11 21:40:00

标签: java multithreading real-time

我写了一个非常简单的玩具程序,根据用户指定的时间要求完成线程内任务的执行。代码和示例输出如下。所发生的是每次运行代码时,任务完成时间将在用户指定的时间的+ delta范围内。例如,如果用户想要在5秒内完成程序,则可以根据运行代码的CPU在5093或5012毫秒内完成。我想添加一些代码,这些代码可以自动确定特定CPU为特定版本的JVM提供的最低延迟。根据该检测代码,可以将delta值添加到行中,如:if (( taskRunTime > patience+delta) && t.isAlive()),以便系统为任务执行时间带来更高的精度。请提出一些建议。

代码:

public class ThreadExample 
{


    static void threadMessage(String message) 
    {
        String threadName = Thread.currentThread().getName();
        System.out.format("%s: %s%n", threadName, message);
    }

    private static class MessageLoop implements Runnable 
    {
        public void run() 
        {
            String importantInfo[] = 
            {
                "A new integrated approach to programming",
                "The innovative approach of the system",
                "The input of a tracking system",
                "A simulation system is then used for collision checking"
            };
            try 
                {
                    for (int i = 0; i < importantInfo.length; i++) 
                        {

                            Thread.sleep(4000);
                            threadMessage(importantInfo[i]);
                        }
                } 
                catch (InterruptedException e) 
                    {
                        threadMessage("I wasn't done!");
                    }
        }
    }

    public static void main(String args[]) throws InterruptedException 
    {


        //Delay, in milliseconds before we interrupt MessageLoop
        long patience = 1000 * 60 * 60;

        //If command line argument present, gives patience in seconds.
        if (args.length > 0) 
        {
            try {
                patience = Long.parseLong(args[0]) * 1000;
            } catch (NumberFormatException e) {
                System.err.println("Argument must be an integer.");
                System.exit(1);
            }

        }

        threadMessage("Starting MessageLoop thread");
        long startTime = System.currentTimeMillis(),taskRunTime=0;
        Thread t = new Thread(new MessageLoop());
        t.start();

        threadMessage("Waiting for MessageLoop thread to finish");
        //loop until MessageLoop thread exits
        while (t.isAlive()) 
        {
            threadMessage("Still waiting...");
            //Wait maximum of 1 second for MessageLoop thread to finish.
            t.join(100);
            taskRunTime=System.currentTimeMillis() - startTime;
            if (( taskRunTime > patience) && t.isAlive()) 
            {
                threadMessage("Tired of waiting...task is running longer than the patience you set or the default!");
                t.interrupt();
                t.join();
            }

        }
        threadMessage("Finally out of thread!");
        System.out.println("Time to complete task="+taskRunTime+"ms");

    }
}

英特尔迅驰1.7 Ghz计算机(Java HotSpot(TM)客户端VM(版本10.0-b23,混合模式))的示例输出

java -jar ThreadExample.jar 5
main: Starting MessageLoop thread
main: Waiting for MessageLoop thread to finish
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
Thread-0: A new integrated approach to programming
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Still waiting...
main: Tired of waiting...task is running longer than the patience you set or the default!
Thread-0: I wasn't done!
main: Finally out of thread!

2 个答案:

答案 0 :(得分:3)

我还写了一些关于behaviour of Thread.sleep和其他可能有用的线程和Java相关内容的东西。

简短的回答是,您将获得的粒度将取决于很多因素,其中一些是动态的。按照您的建议进行检测是前进的方法之一。您需要考虑的工具包括:

  • 在特定条件下要求的实际睡眠行为(请参阅我的文章,了解不同条件下的一些典型行为)
  • 在给定条件下的线程中断延迟(部分取决于CPU负载,系统的调度策略......)

另外,考虑改进控制循环,使其基本上(a)在所需的时间内休眠(在循环中,确保时间休眠),以及(b)在超时后中断线程。

顺便说一句,总是使用System.nanoTime()来计算时间。否则,由于某些系统下System.currentTimeMillis()的粒度很差,你只会感到困惑。

答案 1 :(得分:0)

我建议您查看Java Real Time:http://en.wikipedia.org/wiki/Real_time_Java 还可以查看:http://java.sun.com/j2se/1.5.0/docs/guide/concurrency/overview.html

你不应该在Java 1.5之后编写自己的线程