JavaRush /Java Blog /Random-KO /스레드 중단
Pegas
레벨 34
Гродно

스레드 중단

Random-KO 그룹에 게시되었습니다
. Runnable_ 그들은 간단한 채우기(Thread.sleep 및 sout)를 가지고 있습니다. interrupted및 를 사용하여 스레드를 중단하는 방법을 조사하고 있었습니다 isInterrupted. 어떤 이유로 중단이 발생하지 않지만 프로그램 실행이 루프에 빠지고 오류가 발생합니다. 인터럽트 스레드 - 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)
오류가 발생한 후에도 스레드는 무기한으로 계속 작동합니다. Runnable그러나 에서 상속된 클래스에서 호출을 제거하면 Thread.sleep프로그램이 정상적으로 실행됩니다. 무엇이 문제이고 왜 오류가 발생하며 프로그램이 종료되지 않는 이유는 무엇입니까? 여기 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();
    }
}
1학년:
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");
        }
    }
}
이급:
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");
        }
    }
}
해당 주제에 대한 의견을 보내주셔서 감사합니다)
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION