Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 线程中断不工作_Java_Multithreading_Interrupt - Fatal编程技术网

Java 线程中断不工作

Java 线程中断不工作,java,multithreading,interrupt,Java,Multithreading,Interrupt,这是我第一次尝试创建自己的线程池。除非我尝试停止所有线程,否则该程序将正常工作。 我试图中断所有线程,但由于某种原因,它从未到达此段: if(this.currentThread().isInterrupted()) 这是输出: 添加的所有任务 线程0接收到的任务5 这是任务5 线程2接收到的任务4 这是任务4 线程1接收到的任务3 这是任务3 全部完成,线程池关闭 线程0正在执行任务5 线程0接收到的任务2 这是任务2 线程1正在执行任务3 线程1接收到的任务1 这是任务1 线程2正在执行任务

这是我第一次尝试创建自己的线程池。除非我尝试停止所有线程,否则该程序将正常工作。 我试图中断所有线程,但由于某种原因,它从未到达此段:

if(this.currentThread().isInterrupted())

这是输出:

添加的所有任务
线程0接收到的任务5
这是任务5
线程2接收到的任务4
这是任务4
线程1接收到的任务3
这是任务3
全部完成,线程池关闭
线程0正在执行任务5
线程0接收到的任务2
这是任务2
线程1正在执行任务3
线程1接收到的任务1
这是任务1
线程2正在执行任务4
没有可用的任务…
线程1正在执行任务1
没有可用的任务…
线程0正在执行任务2
没有可用的任务…

调用stopPool()方法后,程序应该停止生成输出

有人能告诉我这里出了什么问题吗

public class CustomThread extends Thread
{
            private int id;
            private Task task;
            private ThreadPool threadpool;

            public CustomThread(int id, Task task, ThreadPool threadpool)
            {
                this.id = id;
                this.task = task;
                this.threadpool = threadpool;
            }

            public synchronized void run()
            {
                while(true)
                {
                    if (this.currentThread().isInterrupted())
                    {
                        System.out.println("Thread " + id + " is halted");
                    }
                    else
                    {
                        if (threadpool.getTaskQueue().isEmpty())
                        {
                            System.out.println("No available tasks...");
                            try 
                            {
                                this.wait();
                            } 
                            catch (InterruptedException e) 
                            {
                                e.printStackTrace();
                            }
                        }
                        else
                        {   
                            task = threadpool.retrieveTask();
                            System.out.println("Task " + task.getID() + " recieved by thread " + id);
                            task.run();
                            task.setState(true);
                            System.out.println("Task " + task.getID() + " now being executed by thread " + id);
                        }
                    }
                }
            }

            public synchronized void wakeUp()
            {
                this.notify();
            }

            public int getThreadID()
            {
                return id;
            }

        }

    import java.util.List;
    import java.util.ArrayList;
    import java.util.Stack;
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.LinkedBlockingQueue;


    public class ThreadPool
    {
        private List<CustomThread> thread_list;
        private Stack<Task> task_queue;

        public ThreadPool(int threads)
        {
            thread_list = new ArrayList<CustomThread>();
            task_queue = new Stack<Task>();
            for(int i=0; i<threads; i++)
            {
                CustomThread thread = new CustomThread(i, null, this);
                thread_list.add(thread);
                thread.start();
            }
        }

        //Must use notify() to wake up an idle thread
        public synchronized void add(Task task)
        {
            task_queue.push(task);
            try
            {
                for(CustomThread t : thread_list)
                {
                    t.wakeUp();
                }

            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        }

        public synchronized void stopPool()
        {
            for(CustomThread t : thread_list)
            {
                t.currentThread().interrupt();
            }

        }

        public synchronized Stack getTaskQueue()
        {
            return task_queue;
        }

        public synchronized Task retrieveTask()
        {
            return task_queue.pop();
        }
    }

public class Task implements Runnable
{
    private int id;
    private boolean finished = false;
    public Task(int id)
    {
        this.id = id;
    }

    public synchronized void run()
    {
            System.out.println("This is task #" + id);

            try
            {
                Thread.sleep(1000);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
    }

    public int getID()
    {
        return id;
    }

    public void setState(Boolean finished)
    {
        this.finished = finished;
    }

    public boolean getState()
    {
        return finished;
    }
}


public class Init 
{
    public static void main(String[] args)
    {
        ThreadPool threadpool = new ThreadPool(3);
        threadpool.add(new Task(1));
        threadpool.add(new Task(2));
        threadpool.add(new Task(3));
        threadpool.add(new Task(4));
        threadpool.add(new Task(5));
        System.out.println("All tasks added");
        {
            try
            {
                Thread.sleep(1000);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        threadpool.stopPool();
        System.out.println("All done, threadpool closed");
    }

}
公共类CustomThread扩展线程
{
私有int-id;
私人任务;
私有线程池线程池;
公共自定义线程(int-id、任务任务、线程池线程池)
{
this.id=id;
this.task=任务;
this.threadpool=threadpool;
}
公共同步的无效运行()
{
while(true)
{
if(this.currentThread().isInterrupted())
{
System.out.println(“线程”+id+“暂停”);
}
其他的
{
if(threadpool.getTaskQueue().isEmpty())
{
System.out.println(“没有可用的任务…”);
尝试
{
这个。等等();
} 
捕捉(中断异常e)
{
e、 printStackTrace();
}
}
其他的
{   
task=threadpool.retrieveTask();
System.out.println(“任务”+Task.getID()+“线程接收”+id);
task.run();
task.setState(true);
System.out.println(“任务”+Task.getID()+”现在由线程“+id”执行);
}
}
}
}
公共同步的无效唤醒()
{
this.notify();
}
public int getThreadID()
{
返回id;
}
}
导入java.util.List;
导入java.util.ArrayList;
导入java.util.Stack;
导入java.util.concurrent.BlockingQueue;
导入java.util.concurrent.LinkedBlockingQueue;
公共类线程池
{
私有列表;
私有堆栈任务队列;
公共线程池(int线程)
{
thread_list=new ArrayList();
任务队列=新堆栈();
对于(int i=0;i您的代码

t.currentThread().interrupt();
将重复中断当前线程,而不是线程
t
try

t.interrupt();
顺便说一句:我希望
wait()
抛出一个异常,您记录该异常并继续,就好像它没有发生一样


出于您的兴趣,您可以使用ExecutorService编写它

ExecutorService service = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 5; i++) {
    final int id = i;
    service.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            System.out.println("This is task #" + id);
            Thread.sleep(1000);
            return null;
        }
    });
}
System.out.println("All tasks added");
service.shutdown();
service.awaitTermination(1, TimeUnit.HOURS);
System.out.println("All done, threadpool closed");

您不应该非静态地引用
Thread.currentThread()
。要扩展David的答案,t.currentThread().interrupt()与Thread.currentThread().interrupt()相同,因此您正在中断当前正在执行的线程,而不是线程t。是的,到目前为止,处理中断的最简单方法是不要在线程循环中捕获
InterruptedException
。我已经实现了您的建议,现在它正在工作。谢谢!
This is task #1
This is task #3
This is task #2
All tasks added
This is task #4
This is task #5
All done, threadpool closed