Cannot restart the stream.

I have the following thread:

public void start() { isRunning = true; if (mainThread == null) { mainThread = new Thread(this); mainThread.setPriority(Thread.MAX_PRIORITY); } if (!mainThread.isAlive()) { try { mainThread.start(); } catch (Exception e) { e.printStackTrace(); } } } 

At some point I want to stop him:

 public void stop() { isRunning = false; System.gc(); } 

When start() is called, the following exception is thrown again:

 java.lang.IllegalThreadStateException 

Specifying a line of code mainThread.start() .

What is the best way to start / stop a thread? how can i make this thread multiple?

Thanks!

+4
source share
2 answers

Once the thread stops you, it won’t be able to restart it in Java, but of course you can create a new thread in Java to complete the new task.

The user interface will not be different even if you create a new thread or restart the same thread (you cannot do this in Java).

You can read the website for the API specification http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html

What you might be looking for is Interrupts . An interruption is an indication of the flow that it should stop what it is doing and do something else. It is up to the programmer to determine exactly how the thread responds to an interrupt, but very often the thread ends.

To learn more about interrupts, read the Java Curriculum Guide http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

+6
source

From your code snippet, it seems that you are using the Runnable class with the Thread attribute. Instead of using stop / start, you can use suspend / resume below:

 private boolean isPaused; public void run() { while (!isRunning) { // do your stuff while (isPaused) { mainThread.wait(); } } } public void suspend() { isPaused = true; } public void resume() { isPaused = false; mainThread.notify(); } 

I did not add synchronized blocks to make the code small, but you will need to add them.

+1
source

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


All Articles