how to temporary disable parallel working threads

T

Thorsten

Hi,

I have a lot of threads working parallel at my program. For time
measurements of some passages of the threads I take same timestamps on
an easy way like:

long t1 = System.currentTimeMillis();
System.out.println("something to do");
long t2 = System.currentTimeMillis();
System.out.println(t2-t1);

But there is a fault: assume I have 100 threads. One thread has just
printed "something to do" and the java vm "decides" to let all other
99 threads run, which takes 10 sec. Now t2 is calculated and has a
value which is 10 sec to high.

Is there a way to say for a thread that some code has to be executed
non-parallel? I think of something like:

atomic {
long t1 = System.currentTimeMillis();
System.out.println("something to do");
long t2 = System.currentTimeMillis();
System.out.println(t2-t1);
}

Does anyone have a hint ?

Regrads
Thorsten
 
G

Gordon Beaton

Is there a way to say for a thread that some code has to be executed
non-parallel? I think of something like:

atomic {
long t1 = System.currentTimeMillis();
System.out.println("something to do");
long t2 = System.currentTimeMillis();
System.out.println(t2-t1);
}

Does anyone have a hint ?

Synchronize the critical section on a common object:

synchronized (foo) {
long t1 = System.currentTimeMillis();
System.out.println("something to do");
long t2 = System.currentTimeMillis();
System.out.println(t2-t1);
}

foo in the example can be any valid object reference, but it must
refer to the *same* object in each of the threads that should be
synchronized. The operation will be mutually atomic among only the
threads sharing the same synchronization object.

/gordon
 
T

Thorsten

Hi Gordon,

thanks a lot, this is a very good hint and it almost works if I get
you right. But the synchronized (foo) {} sections are still
interrupted by other threads if theses other threads are outside their
own synchronized (foo) {} section.

Regards
Thorsten
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top