Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Basic Multithreading

Tags:

java

I would like to ask basic question about Java threads. Let's consider a producer - consumer scenario. Say there is one producer, and n consumer. Consumer arrive at random time, and once they are served they go away, meaning each consumer runs on its own thread. Should I still use run forever condition for consumer ?

public class Consumer extends Thread {
    public void run() {
        while (true) {
        }
    }
}

Won't this keep thread running forever ?

like image 587
Arjun Patel Avatar asked Sep 23 '26 21:09

Arjun Patel


2 Answers

I wouldn't extend Thread, instead I would implement Runnable.

If you want the thread to run forever, I would have it loop forever.

A common alternative is to use

while(!Thread.currentThread().isInterrupted()) {

or

while(!Thread.interrupted()) {
like image 154
Peter Lawrey Avatar answered Sep 26 '26 12:09

Peter Lawrey


It will, so you might want to do something like

while(beingServed)
{
    //check if the customer is done being served (set beingServed to false)
}

This way you'll escaped the loop when it's meant to die.

like image 37
anthonyvd Avatar answered Sep 26 '26 11:09

anthonyvd