JavaRush /Blogue Java /Random-PT /Interromper thread
Pegas
Nível 34
Гродно

Interromper thread

Publicado no grupo Random-PT
Esbocei duas classes que herdam de Runnable. Têm um recheio simples (Thread.sleep e sout). Eu estava pensando em interromper threads usando interruptede isInterrupted. Por algum motivo, a interrupção não ocorre, mas a execução do programa entra em loop e ocorre um erro: Interromper thread - 1
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.javarush.test.myExample.example.thread.Producer.run(Producer.java:15)
	at java.lang.Thread.run(Thread.java:745)
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.javarush.test.myExample.example.thread.Consumer.run(Consumer.java:15)
	at java.lang.Thread.run(Thread.java:745)
Após a ocorrência do erro, os threads continuam funcionando indefinidamente. Mas se você remover Runnablea chamada das classes herdadas de Thread.sleep, o programa será executado normalmente. Qual é o problema, por que ocorre o erro e por que o programa não termina? Aqui main:
public class Solution
{
    public static void main(String[] args) throws InterruptedException
    {
        Thread thread1 = new Thread(new Producer());
        Thread thread2 = new Thread(new Consumer());

        thread1.start();
        thread2.start();

        Thread.sleep(1500);

        thread1.interrupt();
        thread2.interrupt();
    }
}
Primeira série:
public class Producer implements Runnable
{
    @Override
    public void run()
    {
        while (!Thread.interrupted())
        {
            try
            {
                Thread.sleep(100);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            System.out.println("Producer");
        }
    }
}
Segunda classe:
public class Consumer implements Runnable
{
    @Override
    public void run()
    {
        while (!Thread.interrupted())
        {
            try
            {
                Thread.sleep(100);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            System.out.println("Consumer");
        }
    }
}
Obrigado por seus comentários sobre o assunto)
Comentários
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION