开发者

Multithreading in Java

How can I get to know if two threads开发者_JAVA技巧 have started running at the same time on my P4 machine?


You could, for example store the start times in a synchronized map or a hashtable (which is synchronized already):

static Hashtable<Long, Date> starttimes = ...;

and in each Thread's run() method:

starttimes.put(Thread.currentThread().getId(), new Date()); //or use thread names if they are unique

Then you can iterate over the dates and compare them.


On some systems, you could assume that System.nanoTime() is fairly consistent between JVMs. This is not guaranteed but I have found it to be the case.

However, two thread starting at the same time will be so rare, you can fairly safely assume this will never happen. Even two calls to System.nanoTime() can be 100 or more nano-seconds apart. Two calls in different threads are unlikely to return the same value. If even they did, you could not guarantee they started at the same time. Only that one of the first things they did occurred at the same time (to within the accuracy of System.nanoTime())

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜