以下示例汇集了本节的一些概念。 SimpleThreads由两个线程组成。第一个是每个Java应用程序都具有的主线程。主线程从Runnable对象创建一个新线程MessageLoop,并等待其完成。如果MessageLoop线程花费的时间太长,则主线程会中断它。
    MessageLoop线程将打印出一系列消息。如果在打印所有消息之前中断,MessageLoop线程将打印一条消息并退出。

    1. public class SimpleThreads {
    2. // Display a message, preceded by
    3. // the name of the current thread
    4. static void threadMessage(String message) {
    5. String threadName =
    6. Thread.currentThread().getName();
    7. System.out.format("%s: %s%n",
    8. threadName,
    9. message);
    10. }
    11. private static class MessageLoop
    12. implements Runnable {
    13. public void run() {
    14. String importantInfo[] = {
    15. "Mares eat oats",
    16. "Does eat oats",
    17. "Little lambs eat ivy",
    18. "A kid will eat ivy too"
    19. };
    20. try {
    21. for (int i = 0;
    22. i < importantInfo.length;
    23. i++) {
    24. // Pause for 4 seconds
    25. Thread.sleep(4000);
    26. // Print a message
    27. threadMessage(importantInfo[i]);
    28. }
    29. } catch (InterruptedException e) {
    30. threadMessage("I wasn't done!");
    31. }
    32. }
    33. }
    34. public static void main(String args[])
    35. throws InterruptedException {
    36. // Delay, in milliseconds before
    37. // we interrupt MessageLoop
    38. // thread (default one hour).
    39. long patience = 1000 * 60 * 60;
    40. // If command line argument
    41. // present, gives patience
    42. // in seconds.
    43. if (args.length > 0) {
    44. try {
    45. patience = Long.parseLong(args[0]) * 1000;
    46. } catch (NumberFormatException e) {
    47. System.err.println("Argument must be an integer.");
    48. System.exit(1);
    49. }
    50. }
    51. threadMessage("Starting MessageLoop thread");
    52. long startTime = System.currentTimeMillis();
    53. Thread t = new Thread(new MessageLoop());
    54. t.start();
    55. threadMessage("Waiting for MessageLoop thread to finish");
    56. // loop until MessageLoop
    57. // thread exits
    58. while (t.isAlive()) {
    59. threadMessage("Still waiting...");
    60. // Wait maximum of 1 second
    61. // for MessageLoop thread
    62. // to finish.
    63. t.join(1000);
    64. if (((System.currentTimeMillis() - startTime) > patience)
    65. && t.isAlive()) {
    66. threadMessage("Tired of waiting!");
    67. t.interrupt();
    68. // Shouldn't be long now
    69. // -- wait indefinitely
    70. t.join();
    71. }
    72. }
    73. threadMessage("Finally!");
    74. }
    75. }