0

I am experimenting with Multithreading in java, basically I want to make two threads, and have them count to a number.

But when they reach about half way they sleep for a set amount of time. So I was thinking to put an IF statement within the FOR loop to see when it reached halfway and then if it has, it will put itself to sleep.

I am running a single core cpu atm because I am on a school computer so in theroy, when I put the first thread to sleep, the second one should start?

Also, is it possible to put the first thread to sleep, from the second one and vice versa?

Andrei0427
  • 573
  • 3
  • 6
  • 18

5 Answers5

1

You can use the Thread.sleep(int milliseconds):

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

As for making one thread pausing another, you could expose methods which the other threads can call to pause the execution of other threads.

Just like any other multi-threaded program, keep an eye out for race conditions.

As for your other question, single core processors should be able to run multiple threads, so the amount of cores (in this case) does not really matter.

Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
0

A thread may only cause itself to sleep using Thread.sleep. Even when running on a single core CPU, the JVM schedules time for all threads that are available to run. If you want to have more control over when each thread runs you'll want to look into semaphores and other locking/scheduling mechanisms in the java.util.concurrent package.

Ask more specific questions to get help with where you're stuck in your project.

David Harkness
  • 35,992
  • 10
  • 112
  • 134
0

You are getting very close to a race/deadlock conditions when you start having one thread putting other one to sleep and then having itself going to sleep:

http://en.wikipedia.org/wiki/Deadlock#Necessary_conditions

Edmon
  • 4,752
  • 4
  • 32
  • 42
0

I'd recommend you to have a look at this book It covers almost everything about java and concurrency/multithreading, including coding principles and many examples. Book For Conucurrency In java

J.K
  • 2,290
  • 1
  • 18
  • 29
0

For the first part of your question:

It's possible that the second thread may have finished by the time execution reaches the sleep() statement in the first thread. This is because the JVM allocates CPU time to threads not based on when in time each was started, but based on complex scheduling algorithms. The only thing that is guaranteed when you call Thread.sleep(1000) is that the thread WILL stop execution at that point for at least 1000 milliseconds.

The second part - putting one thread to sleep from another - has been addressed well by others. You need to watch out for race conditions.

Rajesh J Advani
  • 5,585
  • 2
  • 23
  • 35