Does anyone see any problems with this thread pattern?

Here is a simple thread template that I use when writing a class that needs only one thread and needs to complete a specific task.

The usual requirements for such a class are that it must be start-up, emergency, and restarted. Does anyone see any problems with this template that I am using?

public class MyThread implements Runnable {
    private boolean _exit = false;
    private Thread _thread = null;

    public void start () {
        _exit = false;

        if (_thread == null) {
            _thread = new Thread(this, "MyThread");
            _thread.start();
        }
    }

    public void run () {
        while (!_exit) {
            //do something
        }
    }

    public void stop () {
        _exit = true;

        if (_thread != null) {
            _thread.interrupt();
            _thread = null;
        }
    }
}

I am looking for comments around if I am missing something, or if there is a better way to write this.

+3
source share
6 answers

, . , . , Thread, , start().

, , , , .

API . Runnable, " , ", Thread. run . , .

, , new Thread(), , . , , .

+2

Thread. , Java 5, , . , , , .

Java Executors .

+6
  • boolean .
  • stop, , _exit true.
  • , try/catch/finally while , , . , !
  • , CountDownLatch - , .

- ... , , , , ( ..).

+2

1) _exit volatile, . stop() , _thread .

2) InterruptedException . , ,

3) , , _exit false start().

+1

(http://java.sun.com/docs/books/tutorial/essential/concurrency/guardmeth.html) 'this'. , "" var. Thread.sleep(x), this.wait(x) () . () , this.notifyAll().

0

_exit . , .: -)

0

Source: https://habr.com/ru/post/1749466/


All Articles