Java thread stop method

Java thread stop method

почему мы еще раз проверяем отработала ли первая нить , если вторая должна запуститься после завершения первой нити ?

Как посмотреть все статьи данного автора? А то написано «Давай вспомним пример из предыдущей лекции» а где эту лекцию найти хз

Зачем проверка isInterrupted в while (!current.isInterrupted()) ? Если использовать while (true), то в Thread.sleep все равно будет проверка и выброс InterruptedException.

Цитата: «Давай вернемся к примеру с часами, который был в лекции основного курса.» Что за «основной курс»?

Конечно я и сам не оратор, но смотреть этот ролик невозможно : ээ, эмм, вот, так вот, вот — тот еще мямля. Простите но это просто не качественный контент разжиженый водичкой . Еще с красным маркером , едва видным, по белому холсту, ужас.

Дело в том, что прямой вызов метода run() не имеет отношения к многопоточности. В этом случае программа будет выполнена в главном потоке — том, в котором выполняется метод main(). Он просто последовательно выведет 10 строк на консоль и все. Никакие 10 потоков не запустятся. Почему же тогда метод getName() выдает 10 разных значений? Откуда 10 разных имён потоков, если всё выполняется в главном потоке? Кто-то может объяснить? Попробовал переписать код с имплементацией Runnable вместо наследования Thread:

 public class MainRunnable < public static void main(String[] args) < for (int i = 0; i < 10; i++) < Thread thread = new Thread(new mulithreading.MyFirstThread2()); thread.run(); >> > class MyFirstThread2 implements Runnable < @Override public void run() < System.out.println("Выполнен поток " + Thread.currentThread().getName()); >> 
 Выполнен поток main Выполнен поток main Выполнен поток main Выполнен поток main Выполнен поток main Выполнен поток main Выполнен поток main Выполнен поток main Выполнен поток main Выполнен поток main 

ВНИМАНИЕ, ВОПРОС! Зачем в методе run в цикле while с условием !current.isInterrupted() при выкидывании InterruptedException мы в блоке catch дополнительно завершаем цикл с помощью break, если в условии цикла у нас уже есть проверка на isInterrupted? По-моему что-то одно следует убрать, либо условие из цикла и оставить только while (true), либо break при обработке исключения.

 public class Clock extends Thread < public static void main(String[] args) throws InterruptedException < Clock clock = new Clock(); clock.start(); Thread.sleep(10000); clock.interrupt(); >public void run() < Thread current = Thread.currentThread(); while (!current.isInterrupted()) < try < Thread.sleep(1000); >catch (InterruptedException e) < System.out.println("Работа потока была прервана"); break; >System.out.println("Tik"); > > > 

Интересно, если есть 4 потока, можно ли сделать так, чтобы: — 1-й поток ждал пока не заверлится 3-й; — 2-й поток ждал пока не заверлится 4-й; и все это параллельно. — 3-й потом работал параллельно 4-му; — после завершение 3-го и 4-го потоков 1-й и 2-й потоки работали также параллельно (при условии что 3-й и 4-й потоки завершились одновременно). Как будет выглядеть код? Метод join(); как я понял, регулирует очередность потоков, но не позволяет «создавать несколько параллельных очередностей» или я не прав? Поясните, пожалуйста, знатоки 🙂

Читайте также:  Iteration over dictionary in python

Источник

How to Stop Thread in Java with Example

Scientech Easy

How to stop a Thread in Java | A thread in Java program will terminate ( or move to dead state) automatically when it comes out of run() method.

But if we want to stop a thread from running or runnable state, we will need to calling stop() method of Thread class. The stop() method is generally used when we desire premature death of a thread.

The general syntax for calling stop method in java programming is as follows:

How to stop a thread in Java

Since the stop() method is static in nature, therefore, it can be called by using Thread class name. When the stop() method is called on a thread, it causes the thread to move to the dead state. Look at the below figure.

As you can observe in the above figure, a thread is terminated when it moves into the dead state either from running or runnable state. If any other thread does not interrupt a thread, it terminates normally.

If a running thread is interrupted then it throws InterruptedException and is terminated. After a thread is gone into the dead state, it cannot be made alive even after the calling of start() method.

If we will try to call start() method on a dead thread, start() method throws an exception named IllegalThreadStateException.

How to stop Running Thread in Java?

Let’s take an example program in which we will kill a running thread by calling stop() method of Thread class.

Program code:

public class Kill extends Thread < // Declare a static variable to of type Thread. static Thread t; public void run() < System.out.println("Thread is running"); t.stop(); // Calling stop() method on Kill Thread. System.out.println("Learn Java step by step"); >public static void main(String[] args) < Kill k = new Kill(); t = new Thread(k); t.start(); // Calling start() method. >>

Explanation:

In the preceding example program, when stop() method is called on a running thread, the next statement is not executed and thread moved into the dead state and is terminated.

How to stop Runnable Thread in Java?

Let’s create a Java program in which we will stop runnable thread in Java. Look at the following source code.

Program code:

public class Thread1 implements Runnable < public void run() < System.out.println("First child thread"); >> public class Thread2 implements Runnable < static Thread t2; public void run() < for(int i = 0; i > >> public class MyThreadClass < public static void main(String[] args) < Thread1 th1 = new Thread1(); Thread2 th2 = new Thread2(); Thread t1 = new Thread(th1); Thread t2 = new Thread(th2); t1.start(); t1.stop(); // Calling stop() method to kill runnable thread. t2.start(); >>
Output: Second child thread: 0 Second child thread: 1 Second child thread: 2 Second child thread: 3 Second child thread: 4 Second child thread: 5 Exception in thread "Thread-1" java.lang.NullPointerException at threadProgram.Thread2.run(Thread2.java:13) at java.lang.Thread.run(Unknown Source)

Explanation:

In this example program, when we called start() method of Thread class on Thread1, the Thread1 moves into the runnable state from newborn state. After Thread1 is moved into the runnable state, it moves into the dead state due to the calling of stop() method on this thread.

Hence, Thread1 is terminated in a runnable state. Similarly, Thread2 is terminated in a running state due to the calling of stop() method after the successful completion of the 4th loop.

Can a thread is again alive when it goes into dead state?

No, when a thread is terminated or moves into dead state, it cannot alive again. If we try to it by calling start() method, we will get an IllegalThreadStateException exception. Let’s take an example program based on it.

Program code:

public class Thread1 implements Runnable < static Thread t1; public void run() < System.out.println("Thread is running"); int i = 0; while(i < 10) < System.out.println("i: " +i); if(i == 5) t1.stop(); i = i + 1; >> public static void main(String[] args) < Thread1 th1 = new Thread1(); Thread t1 = new Thread(th1); t1.start(); t1.start(); // Calling the start() method again to alive a dead thread. >>
Output: Thread is running i: 0 i: 1 i: 2 i: 3 i: 4 i: 5 java.lang.IllegalThreadStateException at java.lang.Thread.start(Unknown Source) at threadEx.Thread1.main(Thread1.java:23)

In this example program, we are invoking start() method to alive a dead thread. Therefore, we got an exception named IllegalThreadStateException.

In all the preceding programs, when you will have called stop() method on a thread, the compiler generates a warning message like “The method stop from type Thread is deprecated”.

This is because the stop() method is deprecated and should not be used. Deprecated method is that method that is no longer in use. It is annotated by a “deprecated” tag in its method heading.

For example, stop(), suspend(), and resume() method are deprecated methods. Java compiler generates a warning whenever a programmer uses method, class, or field with @Deprecated annotation.

Why is stop method deprecated in Java?

In the early days of Java, Thread class defined a stop() method that simply terminates a thread. But later on Java 1.2 version, stop() method had been deprecated. This is because this method is “inherently unsafe” and can cause serious problem sometimes. Therefore, it should not be used in the program for thread safety.

An interviewer can ask you an interesting question that what logic will you use to stop a thread in the place of stop() method because stop() method had been deprecated from Java 1.2.

Basically, there are two ways through which we can easily stop a thread in java program. They are:

1. By using boolean variable.
2. By using isInterrupted() method

Let’s understand these techniques one by one with an example program.

Stopping a thread by using boolean variable

Program code:

public class Thread1 extends Thread < boolean stop = false; public void run() < System.out.println("Thread is running"); int i = 0; while(i < 10) < System.out.println("i: " +i); if(i == 5) if(stop == true) // Come out of run() method. return; i = i + 1; >> public static void main(String[] args) < Thread1 th1 = new Thread1(); Thread t1 = new Thread(th1); t1.start(); th1.stop = true; >>
Output: Thread is running i: 0 i: 1 i: 2 i: 3 i: 4 i: 5

Explanation:

In this example program, first, we created a boolean type variable and initialize it to false. Boolean type variable will store false. Let assume that we want to terminate the thread when i = 5.

So, we will have to store “true” in the boolean type variable. Now, we will check the status of variable in the run() method. If it is true, the thread will execute the return statement and then stop thread.

The syntax to check the status of variable in the run() method is as follows:

Stopping a thread by using isInterrupted() method

To stop a thread using isInterrupted() method, we will modify some code in the previous example program. Look at the following source code.

Program code:

public class Thread1 extends Thread < public void run() < System.out.println("Thread is running"); int i = 0; while(i < 10) < System.out.println("i: " +i); if(i == 5) if(!Thread.currentThread().isInterrupted()) // Come out of run() method. < System.out.println("Status of thread: " +!Thread.currentThread().isInterrupted()); return; >i = i + 1; > > public static void main(String[] args) < Thread1 th1 = new Thread1(); Thread t1 = new Thread(th1); t1.start(); >>
Output: Thread is running i: 0 i: 1 i: 2 i: 3 i: 4 i: 5 Status of thread: true

Explanation:

In this example program, we used isInterrupt() method for stopping a thread. When isInterrupt() method is called on a running thread, the interrupted status of a thread is set by JVM.

It is a boolean flag that is present on every thread. The status of running thread can be checked by calling isInterrupted() method. It returns true if the current thread is interrupted, otherwise returns false.

To check whether the interrupted status of a thread is set or not, first, call Thread.currentThread() method to get current thread and then call isInterrupted method. The complete syntax is given below:

if(!Thread.currentThread().isInterrupted()) < // do more tasks. return; >

The running thread will be terminated when its run() method returns, by executing the return statement, after executing the last statement in the body of method.

interrupted() method is static method that is used to check that the current thread has been interrupted. Calling interrupted() method clears the interrupted status of a thread.

isInterrupted() method is an instance method that is used to that any thread has been interrupted. Calling this method does not change the interrupted status.

Hope that this tutorial has covered all the important points related to how to stop a thread in Java. I hope that you will have understood this topic and enjoy programming.
Thanks for reading.
Next ⇒ Java Thread sleep() method ⇐ PrevNext ⇒

Источник

Оцените статью