0

How can I get to know if two threads have started running at the same time on my P4 machine?

KLCoder
  • 89
  • 2
  • 3
  • 11
  • 6
    The Pentium 4 has a single core, so it's not possible for two threads to start running at the same time. Perhaps a little more detail? – trojanfoe May 09 '11 at 06:59
  • try this, http://stackoverflow.com/questions/861346/in-java-how-do-you-determine-if-a-thread-is-running – cloverink May 09 '11 at 07:00
  • it depends on your definition of "started" and "at the same time". Your question is too vague, please be more specific. – user658991 May 09 '11 at 07:02
  • started= times at which threads start – KLCoder May 09 '11 at 07:03
  • @trojanfoe- I have a program where J3(a thread)is dependent on J1 & J2(also threads) and J5 dependent on J4. Now in J3 I start J1 & J2 and in J5 I start J4. In a seperate program I start running J3 and J5. And availableprocessors that I have is 2. – KLCoder May 09 '11 at 07:05
  • 2
    @KLCoder which precision do you need? Seconds, nanoseconds? As trojanfoe already stated, on a single core machine you can't start threads in the exact same moment, so the time in nanoseconds would differ. – Thomas May 09 '11 at 07:07
  • currently I am using System.nanoTime – KLCoder May 09 '11 at 07:09
  • @KLCoder Note this statement from the `System.nanoTime()` JavaDoc: `This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.` Thus you can't reliably get comparable start times for multiple threads using this method. – Thomas May 09 '11 at 07:13
  • Duplicate of this [question](http://stackoverflow.com/q/3376586/306855). – Emil May 09 '11 at 08:55

2 Answers2

0

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.

Thomas
  • 87,414
  • 12
  • 119
  • 157
0

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())

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130