在以下代码片段中再次调用interrupt()方法的目的是什么?

时间:2017-07-24 00:45:56

标签: java multithreading interrupt interrupt-handling

任何人都可以向我解释为什么 Thread.currentThread()。interrupt(); 在Customer类已经调用它时在Bartender InterruptedException处理程序块中调用。如果我评论该行,' if(Thread.interrupted()){' (在Bartender类的run()方法中)永远不会被调用。

public class Main {
    public static void main(String[] args) {
        Bartender bartender = new Bartender();
        Thread bartenderThread = new Thread(bartender, "Bartender");

        bartenderThread.start();

        // Not very robust, but should allow the bartender to get to sleep first
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            // This can be ignored
        }

        int numCustomers = 1;

        for (int i = 1; i <= numCustomers; i++) {
            String customerName = "Customer " + i;
            Customer customer = new Customer(bartenderThread, customerName, 10);

            new Thread(customer, customerName).start();
        }
    }
}

public class Bartender implements Runnable {
    public void run() {
        System.out.println("Bartender: My boss isn't in today; time for a quick snooze!");

        while (true) {
            if (Thread.interrupted()) { // Check to see if we have been interrupted,
                System.out.println("Bartender: I have to serve customer..");
                System.out.println("Serving customer...........");
                System.out.println("Serving customer DONE");
            }

            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                System.out.println("Bartender Interrupted Exception Handler");
                Thread.currentThread().interrupt();
            }
        }
    }
}

public class Customer implements Runnable {
    private Thread bartenderThread;
    private String name;
    private int waitTime;

    public Customer(Thread bartenderThread, String name, int waitTime) {
        this.bartenderThread = bartenderThread;
        this.name = name;
        this.waitTime = waitTime;
    }

    public void run() {
        System.out.println(name + ": Doesn't seem to be anyone around. I'll wait a moment");

        try {
            TimeUnit.SECONDS.sleep(waitTime);
        } catch (InterruptedException e) {
            // This can be ignored
        }

        System.out.println(name + ": Oh there's a bell! Can I get some service around here?");
        System.out.println("bartenderThread: " + bartenderThread);

        bartenderThread.interrupt(); //
    }
}

0 个答案:

没有答案