Documentation

The Java™ Tutorials
Hide TOC
Questions and Exercises问题和练习
Trail: Essential Java Classes
Lesson: Concurrency

Questions and Exercises: Concurrency问题和练习:并发性

Questions问题

  1. Can you pass a Thread object to Executor.execute? 能否将Thread对象传递给Executor.executeWould such an invocation make sense?这样的调用有意义吗?

Exercises练习

  1. Compile and run BadThreads.java:编译并运行BadThreads.java
    public class BadThreads {
    
        static String message;
    
        private static class CorrectorThread
            extends Thread {
    
            public void run() {
                try {
                    sleep(1000); 
                } catch (InterruptedException e) {}
                // Key statement 1:
                message = "Mares do eat oats."; 
            }
        }
    
        public static void main(String args[])
            throws InterruptedException {
    
            (new CorrectorThread()).start();
            message = "Mares do not eat oats.";
            Thread.sleep(2000);
            // Key statement 2:
            System.out.println(message);
        }
    }

    The application should print out "Mares do eat oats." 应用程序应打印“母马确实吃燕麦。”Is it guaranteed to always do this? If not, why not? 它保证总是这样做吗?若否,原因为何?Would it help to change the parameters of the two invocations of Sleep? 改变两次Sleep调用的参数会有帮助吗?How would you guarantee that all changes to message will be visible in the main thread?您如何保证message的所有更改在主线程中可见?

  2. Modify the producer-consumer example in Guarded Blocks to use a standard library class instead of the Drop class.修改受保护块中的生产者-消费者示例,以使用标准库类而不是Drop类。

Check your answers.检查你的答案。


Previous page: For Further Reading
Next page: The Platform Environment