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.
, . , . , Thread, , start().
, , , , .
API . Runnable, " , ", Thread. run . , .
, , new Thread(), , . , , .
new Thread()
Thread. , Java 5, , . , , , .
Java Executors .
_exit
- ... , , , , ( ..).
1) _exit volatile, . stop() , _thread .
2) InterruptedException . , ,
3) , , _exit false start().
(http://java.sun.com/docs/books/tutorial/essential/concurrency/guardmeth.html) 'this'. , "" var. Thread.sleep(x), this.wait(x) () . () , this.notifyAll().
_exit . , .: -)
Source: https://habr.com/ru/post/1749466/More articles:Как управлять заказами, в которых Java Futures "отправляется"? - javaASP.NET communication from client to server - callbackGet the name of an attribute class or class function as String - scalaIs it good to store files often when using Mercurial or Git? - githttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1749465/how-can-i-use-youtube-chromeless-player-in-desktop-application&usg=ALkJrhjMxsuqaT1fvXQG62JhwMOERD2txwReading XBee data into processing - serial-portПоиск редактора RTF для использования в приложении RCP Eclipse - text-editorHow to build a screenshot programmatically? - c #Translate SQL to OCL? - sqlHow to read line by line only CR file with Perl? - perlAll Articles