{"id":252,"date":"2021-01-21T18:25:32","date_gmt":"2021-01-21T18:25:32","guid":{"rendered":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/?page_id=252"},"modified":"2021-02-05T15:36:59","modified_gmt":"2021-02-05T15:36:59","slug":"threads","status":"publish","type":"page","link":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/","title":{"rendered":"Threads"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a6d495ae5359\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a6d495ae5359\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#What_is_Multithreading\" >What is Multithreading?<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Multithreading_is_the_ability_to_do_or_appear_to_do_more_than_one_thing_at_a_time\" >Multithreading is the ability to do (or appear to do) more than one thing at a time.<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Bouncing_Ball_Demos\" >Bouncing Ball Demos<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#A_non-threaded_bouncing_ball_demo\" >A non-threaded bouncing ball demo.<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#A_threaded_bouncing_ball_demo\" >A threaded bouncing ball demo<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Threads_Thread_Properties\" >Threads &amp; Thread Properties<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#What_is_a_Thread\" >What is a Thread?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Thread_States\" >Thread States<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Daemon_Threads\" >Daemon Threads<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Thread_Operations\" >Thread Operations<\/a><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Creating_a_Thread\" >Creating a Thread<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Stopping_a_Thread\" >Stopping a Thread<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Extending_the_Thread_Class\" >Extending the Thread Class<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Implementing_Runnable\" >Implementing Runnable<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#An_Example\" >An Example<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Some_Useful_Methods\" >Some Useful Methods<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Deprecated_Methods\" >Deprecated Methods<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Thread_Scheduling_Priority\" >Thread Scheduling &amp; Priority<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-19\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Thread_Scheduling\" >Thread Scheduling<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-20\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Preemptive_Scheduling\" >Preemptive Scheduling<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-21\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Non-Preemptive_Scheduling\" >Non-Preemptive Scheduling<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-22\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Thread_Priority\" >Thread Priority<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-23\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Types_of_Threads\" >Types of Threads<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-24\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Unrelated_Threads\" >Unrelated Threads<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-25\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/#Related_but_Unsynchronized_Threads\" >Related but Unsynchronized Threads<\/a><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n\n<p class=\"wp-block-paragraph\">Threads are very important in Java, especially when it comes to GUI programming.&nbsp; Every Java program has <em>at least two threads<\/em>;&nbsp; every Java GUI program has <em>at least three threads<\/em>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_is_Multithreading\"><\/span>What is Multithreading?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Multithreading_is_the_ability_to_do_or_appear_to_do_more_than_one_thing_at_a_time\"><\/span><strong>Multithreading is the ability to do (or appear to do) more than one thing at a time.<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Every Java program is multithreaded, whether you write it to be that way, or not:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The AWT (and JEWT) rely on multithreading to do their work<\/li><li>There is always a&nbsp;<em><strong>garbage collector thread<\/strong><\/em>&nbsp;running in the background<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The Java Virtual Machine is what implements and supports multithreading:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Most JVMs use the native operating system threads on whatever platform they run<\/li><li>Most machines only have a single CPU, and so multiple threads have to share the same CPU, and don&#8217;t actually run concurrently &#8212; they only give the illusion of concurrency.<\/li><li>Some machines have more than a single CPU, and native operating system threads can actually run concurrently.<\/li><li>Some JVMs have to implement their own threads, if the native platforms don&#8217;t provide the necessary support.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Bouncing_Ball_Demos\"><\/span>Bouncing Ball Demos<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Here are some bouncing ball demos:<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"A_non-threaded_bouncing_ball_demo\"><\/span>A non-threaded bouncing ball demo.<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Click the Start button to start bouncing a ball. You&#8217;ll notice that, when you click on the Start button, nothing seems to happen until, finally, the balls appears, at the end of its &#8216;journey&#8217;.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s the source for this program:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage noThreads;\n\nimport java.awt.BorderLayout;\nimport java.awt.Component;\nimport java.awt.Container;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.geom.Rectangle2D;\nimport java.util.ArrayList;\nimport javax.swing.JButton;\nimport javax.swing.JComponent;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport static javax.swing.WindowConstants.EXIT_ON_CLOSE;\n\n\/**\n *\n * @author bryanhiggs\n *\/\npublic class BouncingBallsFrame extends JFrame \n{\n  public static void main(String&#x5B;] args)\n  {\n    BouncingBallsFrame frame = new BouncingBallsFrame();\n    frame.setDefaultLookAndFeelDecorated(true);\n    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);\n    frame.setVisible(true);\n  }\n  \n  public BouncingBallsFrame()\n  {\n    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);\n    setTitle(&quot;Non-threaded Bouncing Balls&quot;);\n\n    canvas = new BallDrawingCanvas();\n    add(canvas, BorderLayout.CENTER);\n    \n    JPanel buttonPanel = new JPanel();\n    add(buttonPanel, BorderLayout.SOUTH);\n    \n    addButton(buttonPanel, &quot;Start&quot;, new ActionListener() \n    {\n      public void actionPerformed(ActionEvent event) \n      {\n        addBall();\n      }\n    });\n\n    addButton(buttonPanel, &quot;Close&quot;, new ActionListener() \n    {\n      public void actionPerformed(ActionEvent event) \n      {\n        System.exit(0);\n      }\n    });\n  }\n  \n  \/**\n   * Adds a button to a container. (Convenience method.)\n   * \n   * @param c\n   *          the container\n   * @param title\n   *          the button title\n   * @param listener\n   *          the action listener for the button\n   *\/\n  public static void addButton(Container c, String title, ActionListener listener) \n  {\n    JButton button = new JButton(title);\n    c.add(button);\n    button.addActionListener(listener);\n  }\n\n  \/**\n   * Adds a bouncing ball to the canvas and starts it bouncing\n   *\/\n  public void addBall() \n  {\n    BouncingBall ball = new BouncingBall(canvas);\n    canvas.add(ball);\n    ball.run();\n  }\n  \n  \/\/ Private data\n  public static final int DEFAULT_WIDTH = 450;\n  public static final int DEFAULT_HEIGHT = 350;\n  \n  private BallDrawingCanvas canvas;  \n}\n\n\/**\n * The Swing Component that draws the balls.\n * \n * @version 1.33 2007-05-17\n * @author Cay Horstmann\n *\/\nclass BallDrawingCanvas extends JComponent \n{\n  \/**\n   * Add a ball to the panel.\n   * \n   * @param b\n   *          the ball to add\n   *\/\n  public void add(BouncingBall b) \n  {\n    balls.add(b);\n  }\n\n  public void paintComponent(Graphics g) \n  {\n    super.paintComponent(g);\n    Graphics2D g2 = (Graphics2D) g;\n    for (BouncingBall ball : balls) \n    {\n      g2.fill(ball.getShape());\n    }\n  }\n\n  \/\/ Private data\n  private ArrayList&lt;BouncingBall&gt; balls = new ArrayList&lt;BouncingBall&gt;();\n}\n\n\/**\n * A ball that moves and bounces off the edges of a rectangle\n * \n * @version 1.33 2007-05-17\n * @author Cay Horstmann\n *\/\nclass BouncingBall \n{\n  \/**\n   * Constructor\n   * Associates the ball with its drawing canvas\n   *\/\n  public BouncingBall(BallDrawingCanvas canvas)\n  {\n      m_canvas = canvas;\n  }\n  \n  \/** \n   * Runs the bouncing ball\n   *\/\n  public void run() \n  {\n    try \n    {\n      for (int i = 1; i &lt;= STEPS; i++) \n      {\n        move(m_canvas.getBounds());\n        m_canvas.repaint();\n        Thread.sleep(DELAY);\n      }\n    } \n    catch (InterruptedException e) \n    {}\n  }\n  \n  \/**\n   * Moves the ball to the next position, reversing direction if it hits one of\n   * the edges\n   *\/\n  public void move(Rectangle2D bounds) \n  {\n    x += dx;\n    y += dy;\n    if (x &lt; bounds.getMinX()) \n    {\n      x = bounds.getMinX();\n      dx = -dx;\n    }\n    if (x + XSIZE &gt;= bounds.getMaxX()) \n    {\n      x = bounds.getMaxX() - XSIZE;\n      dx = -dx;\n    }\n    if (y &lt; bounds.getMinY()) \n    {\n      y = bounds.getMinY();\n      dy = -dy;\n    }\n    if (y + YSIZE &gt;= bounds.getMaxY()) \n    {\n      y = bounds.getMaxY() - YSIZE;\n      dy = -dy;\n    }\n  }\n\n  \/**\n   * Gets the shape of the ball at its current position.\n   *\/\n  public Ellipse2D getShape() \n  {\n    return new Ellipse2D.Double(x, y, XSIZE, YSIZE);\n  }\n\n  \/\/ Private data members\n  \n  private static final int XSIZE = 15;\n  private static final int YSIZE = 15;\n  private double x = 0;\n  private double y = 0;\n  private double dx = 1;\n  private double dy = 1;\n  public static final int STEPS = 1000;\n  public static final int DELAY = 5;\n  \n  private BallDrawingCanvas m_canvas;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s what the above program produces (it&#8217;s a video):<\/p>\n\n\n\n<figure class=\"wp-block-video\"><video height=\"716\" style=\"aspect-ratio: 912 \/ 716;\" width=\"912\" controls src=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-content\/uploads\/2021\/02\/NonThreadingBouncingBalls.mov\"><\/video><\/figure>\n\n\n\n<div style=\"height:12px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"A_threaded_bouncing_ball_demo\"><\/span>A threaded bouncing ball demo<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">By making the implementation multi-threaded, you&#8217;ll find that the applet supports starting a number of balls concurrently. (Just click on the Start button multiple times.)<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s the source for this program:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [37,79,119]; title: ; quick-code: false; notranslate\" title=\"\">\npackage threads;\n\nimport java.awt.BorderLayout;\nimport java.awt.Component;\nimport java.awt.Container;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.geom.Rectangle2D;\nimport java.util.ArrayList;\nimport javax.swing.JButton;\nimport javax.swing.JComponent;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport static javax.swing.WindowConstants.EXIT_ON_CLOSE;\n\n\/**\n * A Class to provide a frame for drawing bouncing balls\n * \n * @author bryanhiggs\n *\/\npublic class BouncingBallsFrame extends JFrame \n{\n  public static void main(String&#x5B;] args)\n  {\n    BouncingBallsFrame frame = new BouncingBallsFrame();\n    frame.setDefaultLookAndFeelDecorated(true);\n    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);\n    frame.setVisible(true);\n  }\n  \n  public BouncingBallsFrame()\n  {\n    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);\n    setTitle(&quot;Threaded Bouncing Balls&quot;);\n\n    canvas = new BallDrawingCanvas();\n    add(canvas, BorderLayout.CENTER);\n    \n    JPanel buttonPanel = new JPanel();\n    add(buttonPanel, BorderLayout.SOUTH);\n    \n    addButton(buttonPanel, &quot;Start&quot;, new ActionListener() \n    {\n      public void actionPerformed(ActionEvent event) \n      {\n        addBall();\n      }\n    });\n\n    addButton(buttonPanel, &quot;Close&quot;, new ActionListener() \n    {\n      public void actionPerformed(ActionEvent event) \n      {\n        System.exit(0);\n      }\n    });\n  }\n  \n  \/**\n   * Adds a button to a container. (Convenience method.)   * \n   *\/\n  public static void addButton(Container c, String title, ActionListener listener) \n  {\n    JButton button = new JButton(title);\n    c.add(button);\n    button.addActionListener(listener);\n  }\n\n  \/**\n   * Adds a bouncing ball to the canvas and starts it bouncing\n   *\/\n  public void addBall() \n  {\n    BouncingBall ball = new BouncingBall(canvas);\n    canvas.add(ball);\n    ball.start();\n  }\n  \n  \/\/ Private data\n  public static final int DEFAULT_WIDTH = 450;\n  public static final int DEFAULT_HEIGHT = 350;\n  \n  private BallDrawingCanvas canvas;  \n}\n\n\/**\n * The Swing Component on which the balls are drawn.\n *\/\nclass BallDrawingCanvas extends JComponent \n{\n  \/**\n   * Add a ball to the canvas.\n   *\/\n  public void add(BouncingBall b) \n  {\n    balls.add(b);\n  }\n\n  public void paintComponent(Graphics g) \n  {\n    super.paintComponent(g);\n    Graphics2D g2 = (Graphics2D) g;\n    for (BouncingBall ball : balls) \n    {\n      g2.fill(ball.getShape());\n    }\n  }\n\n  \/\/ Holds the balls currently being drawn\n  private ArrayList&lt;BouncingBall&gt; balls = new ArrayList&lt;BouncingBall&gt;();\n}\n\n\/**\n * A ball that moves and bounces off the edges of a rectangle\n *\/\nclass BouncingBall extends Thread\n{\n  \/**\n   * Constructor\n   * Associates the ball with its drawing canvas\n   *\/\n  public BouncingBall(BallDrawingCanvas canvas)\n  {\n      m_canvas = canvas;\n  }\n  \n  \/** \n   * Runs the bouncing ball\n   *\/\n  public void run() \n  {\n    try \n    {\n      for (int i = 1; i &lt;= STEPS; i++) \n      {\n        move(m_canvas.getBounds());\n        m_canvas.repaint();\n        Thread.sleep(DELAY);\n      }\n    } \n    catch (InterruptedException e) \n    {}\n  }\n  \n  \/**\n   * Moves the ball to the next position, reversing direction if it hits one of\n   * the edges\n   *\/\n  public void move(Rectangle2D bounds) \n  {\n    x += dx;\n    y += dy;\n    if (x &lt; bounds.getMinX()) \n    {\n      x = bounds.getMinX();\n      dx = -dx;\n    }\n    if (x + XSIZE &gt;= bounds.getMaxX()) \n    {\n      x = bounds.getMaxX() - XSIZE;\n      dx = -dx;\n    }\n    if (y &lt; bounds.getMinY()) \n    {\n      y = bounds.getMinY();\n      dy = -dy;\n    }\n    if (y + YSIZE &gt;= bounds.getMaxY()) \n    {\n      y = bounds.getMaxY() - YSIZE;\n      dy = -dy;\n    }\n  }\n\n  \/**\n   * Gets the shape of the ball at its current position.\n   *\/\n  public Ellipse2D getShape() \n  {\n    return new Ellipse2D.Double(x, y, XSIZE, YSIZE);\n  }\n\n  \/\/ Private data members\n  \n  private static final int XSIZE = 15;\n  private static final int YSIZE = 15;\n  private double x = 0;\n  private double y = 0;\n  private double dx = 1;\n  private double dy = 1;\n  public static final int STEPS = 1000;\n  public static final int DELAY = 5;\n  \n  private BallDrawingCanvas m_canvas;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">This program is very slightly modified from the first, non-threaded, version, and now works correctly. It allows the user to click on the Start button multiple times, each time creating a new bouncing balls, and multiple balls may now be seen on the window. See the following video:<\/p>\n\n\n\n<figure class=\"wp-block-video\"><video height=\"716\" style=\"aspect-ratio: 912 \/ 716;\" width=\"912\" controls src=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-content\/uploads\/2021\/02\/ThreadedBouncingBalls.mov\"><\/video><\/figure>\n\n\n\n<div style=\"height:60px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Threads_Thread_Properties\"><\/span>Threads &amp; Thread Properties<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s talk about threads and their properties.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_is_a_Thread\"><\/span>What is a Thread?<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">A&nbsp;<em>thread of control<\/em>&nbsp;in a program.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each thread:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Starts at some predefined location<\/li><li>Executes in its own context, independent of other threads in the program<\/li><li>May choose to cooperate with one or more threads in the program<\/li><li>Appears to have a degree of simultaneous execution (in the case of multiple CPUs, may actually execute simultaneously with other threads in the program)<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Java has a class,&nbsp;<strong>Thread<\/strong>, which provides an abstraction to support the concept of a thread within a Java Virtual Machine. It, together with other Java features, provides the necessary functionality and context to allow Java programmers to write multithreaded programs.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Thread_States\"><\/span>Thread States<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"alignleft size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"349\" height=\"346\" src=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-content\/uploads\/2021\/02\/threadStates.gif\" alt=\"\" class=\"wp-image-260\"\/><\/figure><\/div>\n\n\n\n<div style=\"height:10px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<ul class=\"wp-block-list\"><li>When a thread is first created, it enters the NEW state, at which point it is not executing<\/li><li>When the thread&#8217;s&nbsp;<strong>start()<\/strong>&nbsp;method is invoked, the thread changes to the RUNNABLE state.<\/li><li>When the thread is RUNNABLE, it is&nbsp;<em>eligible<\/em>&nbsp;for execution, but&nbsp;<em>not necessarily running<\/em>.<\/li><li>When certain events happen to a RUNNABLE thread, it may enter the NOT RUNNABLE state, where it is still alive, but not eligible for execution. Such events include:<ul><li>Thread is waiting for an I\/O operation to complete<\/li><li>Thread has put itself to sleep for a certain period of time (by calling&nbsp;<strong>sleep()<\/strong>)<\/li><li>Thread has called&nbsp;<strong>wait()<\/strong><\/li><li>Thread has called&nbsp;<strong>yield()<\/strong><\/li><\/ul><\/li><li>A NOT RUNNABLE thread becomes RUNNABLE again when the condition that caused the thread to become NOT RUNNABLE ends:<ul><li>I\/O completes<\/li><li>Sleep period expires<\/li><li>etc.<\/li><\/ul><\/li><li>When the thread terminates, it becomes DEAD &#8212; permanently! Once the thread enters the DEAD state, there is no way to resuscitate it. There are a number of ways a thread may terminate, including:<ul><li>By returning from its&nbsp;<strong>run()<\/strong>&nbsp;method (<em>this is the recommended approach<\/em>)<\/li><li>By being stopped (dangerous! &#8212; don&#8217;t do it!)<\/li><\/ul><\/li><\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Daemon_Threads\"><\/span>Daemon Threads<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Some threads are intended to be &#8220;background&#8221; threads, providing services to other threads. These threads are called&nbsp;<em><strong>daemon threads<\/strong><\/em>.&nbsp;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">UNIX has a similar concept for processes, where certain operating system services are provided by&nbsp;<em><strong>daemon processes<\/strong><\/em>.&nbsp; (For some reason, it has become traditional to use the archaic spelling for demon.)&nbsp; Microsoft Windows uses&nbsp;<em>Windows services<\/em>&nbsp;for similar operations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When a Java thread is created, it is a&nbsp;<em><strong>non-daemon thread<\/strong><\/em>. It may be changed (or change itself) to a daemon thread by calling its&nbsp;<strong>setDaemon()<\/strong>&nbsp;method. (There is also a matching&nbsp;<strong>isDaemon()<\/strong>&nbsp;method.)<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When a Java Virtual Machine starts up, there is usually a single non-<em>daemon<\/em>&nbsp;thread (which typically calls the method named&nbsp;<strong>main<\/strong>&nbsp;of some designated class), and one&nbsp;<em><strong>daemon thread<\/strong><\/em>&nbsp;&#8212; the&nbsp;<em><strong>garbage collection thread<\/strong><\/em>. The Java Virtual Machine continues to execute threads until either of the following occurs:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The&nbsp;<strong>exit<\/strong>&nbsp;method of class&nbsp;<strong>Runtime<\/strong>&nbsp;has been called (<strong>System.exit()<\/strong>&nbsp;calls this method) and the security manager has permitted the exit operation to take place,<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">or:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>All threads that are not&nbsp;<em><strong>daemon<\/strong><\/em>&nbsp;threads have died, either by returning from the call to the&nbsp;<strong>run<\/strong>&nbsp;method or by their&nbsp;<strong>stop<\/strong>&nbsp;(deprecated!)method being called.<\/li><\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Thread_Operations\"><\/span>Thread Operations<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the most fundamental of thread operations:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">How to <strong><em>start<\/em><\/strong>, <strong><em>stop<\/em><\/strong>, and <strong><em>run<\/em><\/strong> a thread.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_a_Thread\"><\/span>Creating a Thread<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">There are two ways of&nbsp;<em><strong>creating a thread<\/strong><\/em>:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Using a class that extends the&nbsp;<strong>Thread<\/strong>&nbsp;class<\/li><li>Using a class that implements the&nbsp;<strong>Runnable<\/strong>&nbsp;interface (note that&nbsp;<code>Thread<\/code>&nbsp;implements&nbsp;<code>Runnable<\/code>)<\/li><\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">You&nbsp;<em><strong>start a thread<\/strong><\/em>&nbsp;by calling&nbsp;<strong>Thread<\/strong>&#8216;s&nbsp;<strong>start()<\/strong>&nbsp;method from some thread. The&nbsp;<strong>start()<\/strong>&nbsp;method does the following:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Creates a separate thread of execution<\/li><li>Starts that thread of execution at the&nbsp;<strong>Thread<\/strong>&#8216;s or <strong>Runnable<\/strong>&#8216;s <strong>run()<\/strong> method<\/li><li>Returns from the&nbsp;<strong>start()<\/strong>&nbsp;call in the starting thread.<\/li><\/ol>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Stopping_a_Thread\"><\/span>Stopping a Thread<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">You&nbsp;<em><strong>stop a thread<\/strong><\/em>&nbsp;by causing the thread to return from its&nbsp;<strong>run()<\/strong>&nbsp;execution.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong><em><u>Note:<\/u><\/em><\/strong>&nbsp;There is a&nbsp;<strong>stop()<\/strong>&nbsp;method in the&nbsp;<strong>Thread<\/strong>&nbsp;class, but its use is now deprecated, because it is inherently unsafe.&nbsp;<strong><em>DO NOT USE THIS METHOD!<\/em><\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, here is a typical&nbsp;<strong>run()<\/strong>&nbsp;method for a thread that will terminate after doing a finite amount of work:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public void run() \n{\n   for (int i = 0; i &lt; 100; i++) \n   {\n      doWork();\n   }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It simply terminates after a finite number of iterations through its work loop. Of course, the&nbsp;<strong>run()<\/strong>&nbsp;method is not required to loop at all; the thread may be doing one-time-only type work, and simply return when it has finished.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Some threads, once started, loop forever until some outside event causes them to terminate the loop. Here is how you typically write code to cause a thread to stop prematurely:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public class MyThreadOrRunnable ...\n{\n    ...\n\n   public void run() \n   {\n      <strong>while (m_running) <\/strong>\n      {\n         doFiniteWork();\n      }\n   }\n\n   <strong>public void stopExecution()\n   {\n      m_running = false;\n   }\n\n   private boolean m_running = true;<\/strong>\n}<\/pre>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p><strong><em>Note:<\/em><\/strong>&nbsp;Do not use the&nbsp;<strong>Thread<\/strong>&#8216;s&nbsp;<strong>stop()<\/strong>&nbsp;method!<\/p><\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">This is a simple case. If&nbsp;<strong>doWork()<\/strong>&nbsp;can take some time, and if you wish the thread to respond quickly to the request to stop its execution, then you must arrange for the code to check for the change of status on a regular basis.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Canceling an executing thread is a non-trivial exercise. <\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>For more details, see&nbsp;<a rel=\"noreferrer noopener\" href=\"http:\/\/gee.cs.oswego.edu\/dl\/cpj\/cancel.html\" target=\"_blank\">Doug Lea&#8217;s &#8220;Cancelable Activities&#8221;<\/a>.&nbsp; In general, Doug Lea&#8217;s &#8220;Concurrent Programming in Java&#8221; is an excellent detailed reference for advanced use of threads in Java. See his&nbsp;<a rel=\"noreferrer noopener\" href=\"http:\/\/gee.cs.oswego.edu\/dl\/cpj\/index.html\" target=\"_blank\">Online Supplement<\/a>.<\/p><\/blockquote>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Extending_the_Thread_Class\"><\/span>Extending the Thread Class<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">One way of implementing a thread is to create a class that extends from the <strong>java.lang.Thread<\/strong> class, and that then overrides the&nbsp;<strong>run()<\/strong>&nbsp;method.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example of how to extend from class&nbsp;<strong>Thread<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [3,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36]; title: ; quick-code: false; notranslate\" title=\"\">\npackage threads;\n\npublic class CountDownThread extends Thread\n{\n  public CountDownThread(String name, int countDown,\n                         CountDownProgress progress)\n  {\n    super(name);\n    m_countDown = countDown;\n    m_progress = progress;\n  }\n  \n  \/\/ The method that does the work of the thread\n  public void run()\n  {\n    m_progress.started(getName() + \n                       &quot;: started (counting from &quot; +\n                       m_countDown + &quot;)&quot;);\n    try\n    {\n      for (int i = m_countDown; i &gt;= 0; i--)\n      {\n        sleep(1000);    \/\/ Sleep for 1 second\n        \/\/ Audible &#039;tick&#039;\n        m_progress.tick(getName() + &quot;: &quot; + i);\n      }\n    }\n    catch (InterruptedException e)\n    {\n      \/\/ Ignore\n    }\n    finally\n    {\n      m_progress.done(getName() + &quot;: done!&quot;);\n    }\n  }\n  \n  \/\/\/\/\/\/\/ Private data \/\/\/\/\/\/\/\n  private int m_countDown;\n  private CountDownProgress m_progress;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Notice that it uses a&nbsp;<strong>CountDownProgress<\/strong> interface:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage threads;\n\n\/**\n * Interface to provide a simple progress\n * for the CountDownThread.\n *\/\npublic interface CountDownProgress\n{\n  public void started(String message);\n  \n  public void tick(String message);\n  \n  public void done(String message);\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">and here&#8217;s a program to test it out:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage threads;\n\nimport java.util.Random;\n\npublic class CountDownThreadTester implements CountDownProgress\n{\n  \/**\n   *   Main entry point.\n   *\n   *   Arguments: list of thread names to use.\n   *\/\n  public static void main(String&#x5B;] args)\n  {\n    Random random = new java.util.Random();\n    CountDownThreadTester tester = new CountDownThreadTester();\n    int threadCount = 5;\n    for (int i = 1; i &lt;= threadCount; i++)\n    {\n      \/\/ Generate a random number between 5 and 10\n      int countDown = random.nextInt(5) + 5;\n      CountDownThread thread = \n          new CountDownThread(&quot;Thread &quot; + i, countDown, tester);\n      thread.start();\n    }\n  }\n  \n  public void started(String message)\n  {\n    System.err.println(message);\n  }\n  \n  public void tick(String message)\n  {\n    System.err.println(message);\n  }\n  \n  public void done(String message)\n  {\n    System.err.println(message);\n  }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">In other words, it creates 5 threads, telling each to count down starting from a value somewhere between 5 and 10.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Note that the above test program implements the <strong>CountDownProgress<\/strong> interface, and outputs the resulting messages to&nbsp;<strong>System.err&nbsp;<\/strong>&#8212; intentional, because&nbsp;<strong>System.err<\/strong>&nbsp;is not buffered.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When I ran this, it produced the following output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Thread 1: started (counting from 7)\nThread 2: started (counting from 7)\nThread 3: started (counting from 6)\nThread 4: started (counting from 7)\nThread 5: started (counting from 6)\nThread 1: 7\nThread 5: 6\nThread 4: 7\nThread 3: 6\nThread 2: 7\nThread 1: 6\nThread 5: 5\nThread 3: 5\nThread 4: 6\nThread 2: 6\nThread 1: 5\nThread 3: 4\nThread 5: 4\nThread 4: 5\nThread 2: 5\nThread 1: 4\nThread 2: 4\nThread 4: 4\nThread 5: 3\nThread 3: 3\nThread 1: 3\nThread 5: 2\nThread 4: 3\nThread 2: 3\nThread 3: 2\nThread 1: 2\nThread 2: 2\nThread 4: 2\nThread 5: 1\nThread 3: 1\nThread 1: 1\nThread 2: 1\nThread 4: 1\nThread 5: 0\nThread 5: done!\nThread 3: 0\nThread 3: done!\nThread 1: 0\nThread 1: done!\nThread 4: 0\nThread 4: done!\nThread 2: 0\nThread 2: done!<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It should be evident that the threads are running asynchronously.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Implementing_Runnable\"><\/span>Implementing Runnable<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">There are, however, situations where you want to have a class do thread work, but you also need that class to extend from another class. Since Java doesn&#8217;t allow you to extend from more than a single class, you wouldn&#8217;t be able to use the previous technique.&nbsp;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this case, you&#8217;ll need to use the&nbsp;<strong>Runnable<\/strong>&nbsp;interface instead. In general, you may prefer to use the <strong>Runnable<\/strong>&nbsp;technique, because it&#8217;s more flexible.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s how you do the same thing as above, but using the <strong>Runnable<\/strong> interface:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [3,22,37,38,39,40,41,42,43]; title: ; quick-code: false; notranslate\" title=\"\">\npackage threads;\n\npublic class CountDownRunnable implements Runnable\n{\n  public CountDownRunnable(int countDown,\n                           CountDownProgress progress)\n  {\n    m_countDown = countDown;\n    m_progress = progress;\n  }\n  \n  \/\/ The method that does the work of the thread\n  public void run()\n  {\n    m_progress.started(getName() + \n                       &quot;: started (counting from &quot; +\n                       m_countDown + &quot;)&quot;);\n    try\n    {\n      for (int i = m_countDown; i &gt;= 0; i--)\n      {\n        Thread.sleep(1000);    \/\/ Sleep for 1 second\n        \/\/ Audible &#039;tick&#039;\n        m_progress.tick(getName() + &quot;: &quot; + i);\n      }\n    }\n    catch (InterruptedException e)\n    {\n      \/\/ Ignore\n    }\n    finally\n    {\n      m_progress.done(getName() + &quot;: done!&quot;);\n    }\n  }\n  \n  \/**\n   * Gets the name of the thread this is running\n   *\/\n  private String getName()\n  {\n    return Thread.currentThread().getName();\n  }\n   \n  \/\/\/\/\/\/\/ Private data \/\/\/\/\/\/\/\n  private int m_countDown;\n  private CountDownProgress m_progress;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">and here&#8217;s the corresponding test program:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [5,21,22,23,24]; title: ; quick-code: false; notranslate\" title=\"\">\npackage threads;\n\nimport java.util.Random;\n\npublic class CountDownRunnableTester implements CountDownProgress\n{\n  \/**\n   *   Main entry point.\n   *\n   *   Arguments: list of thread names to use.\n   *\/\n  public static void main(String&#x5B;] args)\n  {\n    Random random = new java.util.Random();\n    CountDownRunnableTester tester = new CountDownRunnableTester();\n    int threadCount = 5;\n    for (int i = 1; i &lt;= threadCount; i++)\n    {\n      \/\/ Generate a random number between 5 and 10\n      int countDown = random.nextInt(5) + 5;\n      CountDownRunnable runnable = \n          new CountDownRunnable(countDown, tester);\n      Thread thread = new Thread(runnable, &quot;Thread &quot; + i);\n      thread.start();\n    }\n  }\n  \n  public void started(String message)\n  {\n    System.err.println(message);\n  }\n  \n  public void tick(String message)\n  {\n    System.err.println(message);\n  }\n  \n  public void done(String message)\n  {\n    System.err.println(message);\n  }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">We still use the&nbsp;<strong>Thread<\/strong>&nbsp;class to cause a thread to start, but now we use it directly, specifying in the <strong>Thread<\/strong>&nbsp;constructor the class that implements the <strong>Runnable<\/strong> interface, to associate the runnable class with the thread.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The effect of using the&nbsp;<strong>Runnable<\/strong>&nbsp;interface is to separate the work (the code in the <strong>run()<\/strong> method) from the context in which it runs (the thread).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s what this program produced on my machine when I ran it (note that the actual output may vary because of the nature of multi-threading applications):<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Thread 1: started (counting from 6)\nThread 2: started (counting from 7)\nThread 3: started (counting from 9)\nThread 4: started (counting from 6)\nThread 5: started (counting from 9)\nThread 1: 6\nThread 2: 7\nThread 3: 9\nThread 4: 6\nThread 5: 9\nThread 1: 5\nThread 2: 6\nThread 3: 8\nThread 4: 5\nThread 5: 8\nThread 2: 5\nThread 1: 4\nThread 5: 7\nThread 4: 4\nThread 3: 7\nThread 2: 4\nThread 1: 3\nThread 5: 6\nThread 3: 6\nThread 4: 3\nThread 2: 3\nThread 1: 2\nThread 5: 5\nThread 4: 2\nThread 3: 5\nThread 2: 2\nThread 1: 1\nThread 5: 4\nThread 3: 4\nThread 4: 1\nThread 2: 1\nThread 1: 0\nThread 1: done!\nThread 5: 3\nThread 4: 0\nThread 4: done!\nThread 3: 3\nThread 2: 0\nThread 2: done!\nThread 5: 2\nThread 3: 2\nThread 5: 1\nThread 3: 1\nThread 5: 0\nThread 5: done!\nThread 3: 0\nThread 3: done!<\/strong><\/pre>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"An_Example\"><\/span>An Example<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Here is an example of a program that uses the&nbsp;<strong>Runnable<\/strong>&nbsp;interface technique: <em>a clock <\/em>program<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s the source for this program. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Note how the program causes the thread to stop, by setting the <strong>m_clockThread<\/strong> field to <strong>null<\/strong>, thus causing the thread&#8217;s run loop to terminate.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage threads;\n\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.EventQueue;\nimport java.awt.Font;\nimport java.awt.Graphics;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.text.DateFormat;\nimport javax.swing.BorderFactory;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.SwingConstants;\nimport static javax.swing.WindowConstants.EXIT_ON_CLOSE;\n\n\/**\n * Class to display the current time, updated every second,\n * using threads\n *\/\npublic class Clock extends JPanel implements Runnable\n{\n  \/**\n   * Main entry point\n   *\/\n  public static void main(String&#x5B;] args)\n  {\n    JFrame frame = new JFrame(&quot;Clock&quot;);\n    frame.setDefaultLookAndFeelDecorated(true);\n    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);\n    frame.setSize(300, 200);\n    \n    JPanel contentPane = (JPanel) frame.getContentPane();\n    contentPane.setLayout(new BorderLayout());\n    \n    \/\/ Add the Clock canvas to the content pane, to the CENTER\n    Clock clockCanvas = new Clock();\n    contentPane.add(clockCanvas, BorderLayout.CENTER);\n    \n    \/\/ Construct the button panel\n    JPanel buttonPanel = new JPanel();\n    buttonPanel.setBorder(BorderFactory.createLineBorder(Color.lightGray));\n    contentPane.add(buttonPanel, BorderLayout.SOUTH);\n    \n    \/\/ Add the Start button\n    addButton(buttonPanel, &quot;Start&quot;, \n              new ActionListener()\n                {  \n                  public void actionPerformed(ActionEvent evt)\n                  {\n                    clockCanvas.start(); \/\/ Start the ball bouncing\n                  }\n                }\n              );\n    \/\/ Add the Stop button\n    addButton(buttonPanel, &quot;Stop&quot;, \n              new ActionListener()\n                {  \n                  public void actionPerformed(ActionEvent evt)\n                  {\n                    clockCanvas.stop();\n                  }\n                }\n              );\n    \n    frame.setVisible(true);\n  }\n  \n  \/**\n   * Convenience method for adding a button to a panel\n   * @param panel - the panel to use\n   * @param title - the button title\n   * @param listener - the button&#039;s action listener\n   *\/\n  private static void addButton(JPanel panel, \n                                String title, \n                                ActionListener listener)\n  {\n    JButton button = new JButton(title);\n    panel.add(button);\n    button.addActionListener(listener);\n  }\n  \n  \/**\n   * Constructor\n   *\/\n  private Clock()\n  {\n    EventQueue.invokeLater( new Runnable()\n      {\n        public void run()\n        {\n          m_timeLabel = new JLabel(&quot;The Time is...&quot;, SwingConstants.CENTER);\n          m_timeLabel.setFont( new Font(&quot;Dialog&quot;, Font.BOLD, 16) );\n          add(m_timeLabel);\n        }\n      }\n    );\n  }\n  \n  \/**\n   * Start the clock\n   * Starts up the thread to keep the clock updated.\n   *\/\n  private void start()\n  {\n    if (m_clockThread == null)\n    {\n      m_clockThread = new Thread(this, &quot;Clock&quot;);\n      m_clockThread.start();\n    }\n  }\n  \n  \/**\n   * The Runnable run method for this Clock\n   * Keeps the clock updated every second.\n   *\/\n  public void run()\n  {\n    \/\/ Loop until m_clockThread is set to null\n    while (m_clockThread != null)\n    {\n      try\n      {\n        Thread.sleep(1000); \/\/ For 1 second\n        \/\/ Change the label to the current time\n        EventQueue.invokeLater( new Runnable()\n          {\n            \/\/ Update the label in the event handling thread.\n            public void run()\n            {\n              Calendar cal = Calendar.getInstance();\n              Date date = cal.getTime();\n              DateFormat dateFormatter = DateFormat.getTimeInstance();\n              m_timeLabel.setText(dateFormatter.format(date));\n            }\n          }\n        );\n      }\n      catch (InterruptedException e)\n      {\n        \/\/ Ignore\n      }\n    }\n  }\n  \n  \/**\n   * Stop the clock\n   *\/\n  private void stop()\n  {\n    m_clockThread = null; \/\/ Will cause the thread to end\n  }\n  \n  \/\/\/\/\/\/\/ Private data \/\/\/\/\/\/\/\/\/\/\/\n  private Thread m_clockThread = null;\n  private JLabel m_timeLabel;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">which produces the following (a video):<\/p>\n\n\n\n<figure class=\"wp-block-video alignleft\"><video height=\"404\" style=\"aspect-ratio: 602 \/ 404;\" width=\"602\" controls src=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-content\/uploads\/2021\/02\/Screen-Recording-2021-02-03-at-3.09.10-PM-1.mov\"><\/video><\/figure>\n\n\n\n<div style=\"height:13px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Some_Useful_Methods\"><\/span>Some Useful Methods<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Here are some useful methods provided by the&nbsp;<strong>Thread<\/strong>&nbsp;class:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Method<\/strong><\/td><td><strong>Description<\/strong><\/td><\/tr><tr><td>public Thread()<\/td><td>Constructs a new Thread object, with an automatically generated name<\/td><\/tr><tr><td>public Thread(String name)<\/td><td>Constructs a new Thread object, with the specified name<\/td><\/tr><tr><td>public Thread(Runnable target)<\/td><td>Constructs a new Thread object, with the associated Runnable object and an automatically generated name<\/td><\/tr><tr><td>public Thread(Runnable target, String name)<\/td><td>Constructs a new Thread object, with the associated Runnable object and the specified name.<\/td><\/tr><tr><td>public static Thread currentThread()<\/td><td>Returns a reference to the currently executing thread object.<\/td><\/tr><tr><td>public static void dumpStack()<\/td><td>Prints a stack trace of the current thread. This method is used only for debugging<\/td><\/tr><tr><td>public final String getName()<\/td><td>Returns this thread&#8217;s name.<\/td><\/tr><tr><td>public void interrupt()<\/td><td>Interrupts this thread.<\/td><\/tr><tr><td>public final boolean isAlive()<\/td><td>Tests if this thread is alive. A thread is alive if it has been started and has not yet died.<\/td><\/tr><tr><td>public final void setName( String name)<\/td><td>Changes the name of this thread to be equal to the argument name.<\/td><\/tr><tr><td>public static void sleep( long millis) throws InterruptedException<\/td><td>Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.<\/td><\/tr><tr><td>public static void sleep( long millis, int nanos) throws InterruptedException<\/td><td>Causes the currently executing thread to sleep (cease execution) for the specified number of milliseconds plus the specified number of nanoseconds.<\/td><\/tr><tr><td>public synchronized void start()<\/td><td>Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.<\/td><\/tr><tr><td>public static void yield()<\/td><td>Causes the currently executing thread object to temporarily pause and allow other threads to execute.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Deprecated_Methods\"><\/span>Deprecated Methods<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The following thread methods have been deprecated since JDK 1.2:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>stop()<\/strong><\/li><li><strong>suspend()<\/strong><\/li><li><strong>resume()<\/strong><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The&nbsp;<strong>stop()<\/strong>&nbsp;method is inherently unsafe, and the <strong>suspend()<\/strong> and <strong>resume()<\/strong> methods are deadlock-prone.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em><strong>They should not be used!<\/strong><\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For details, see&nbsp;<a rel=\"noreferrer noopener\" href=\"http:\/\/java.sun.com\/j2se\/1.5.0\/docs\/guide\/misc\/threadPrimitiveDeprecation.html\" target=\"_blank\">here<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Thread_Scheduling_Priority\"><\/span>Thread Scheduling &amp; Priority<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Thread_Scheduling\"><\/span>Thread Scheduling<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Thread scheduling is the mechanism used to allocate CPU time to threads.<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are two basic types of thread scheduling:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Preemptive<\/li><li>Non-preemptive<\/li><\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Preemptive_Scheduling\"><\/span>Preemptive Scheduling<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In this type of scheduling, the scheduler preempts a running thread to allow other threads to run. The process of switching from one thread running to another thread running is transparent to the writer of the thread code.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Non-Preemptive_Scheduling\"><\/span>Non-Preemptive Scheduling<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Here, the scheduler never interrupts a running thread. Instead, the thread code is expected to cooperate and&nbsp;<em>yield<\/em>&nbsp;control at the appropriate times so that other threads can execute. If a thread does not cooperate, it may cause other threads to&nbsp;<em>starve<\/em>&nbsp;(never get CPU time). for example, if a thread has code like:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>while (forALongTime)\n{\n    codeThatDoesNotYieldNorBlock();\n}<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">then, with a non-preemptive scheduler, no other threads would get scheduled while this thread was running this piece of code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are some things to do when you are writing code that must run in a thread with a non-preemptive scheduler:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Don&#8217;t loop for a long time executing code that does not yield, nor sleeps, nor does blocking I\/O.<\/li><li>Occasionally call&nbsp;<strong>yield()<\/strong>&nbsp;when performing CPU-intensive operations.<\/li><li>Lower the priority of CPU-intensive threads (but they still need to yield).<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Writing for&nbsp;<em>preemptive<\/em>&nbsp;thread models is easier than writing for&nbsp;<em>non-preemptive<\/em>&nbsp;thread models. Note that, if you are trying to write portable Java code, and you&#8217;re developing on a platform that uses preemptive threads, you can&#8217;t make assumptions that all Java platforms will provide this level of thread support.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Thread_Priority\"><\/span>Thread Priority<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Different native operating system threads have different thread priority schemes. The Java&nbsp;Thread&nbsp;class attempts to accommodate these in its abstraction.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the Thread class, there are the following constants:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td>public static final int MAX_PRIORITY<\/td><td>The maximum priority that a thread can have.<\/td><\/tr><tr><td>public static final int MIN_PRIORITY<\/td><td>The minimum priority that a thread can have.<\/td><\/tr><tr><td>public static final int NORM_PRIORITY<\/td><td>The default priority assigned to a thread.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">which are mapped to the native thread priorities.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are also the following methods in class&nbsp;Thread:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td>public final int getPriority()<\/td><td>Returns this thread&#8217;s priority.<\/td><\/tr><tr><td>public final void setPriority( int newPriority)<\/td><td>Changes the priority of this thread.<br>(The priority must be in the range MIN_PRIORITY to MAX_PRIORITY, and the calling thread must have the proper access rights to change the thread priority.)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The&nbsp;<strong>setPriority()<\/strong>&nbsp;method may be called to change the priority of a thread. Typically, the call would look like:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>thread.setPriority(NORM_PRIORITY + 1);<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">or:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>thread.setPriority(NORM_PRIORITY - 3);<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Be aware:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>It should only be necessary to make small changes to a thread&#8217;s priority.<\/li><li>If you elevate too many threads&#8217; priorities to MAX_PRIORITY (or close to it), priority will quickly become meaningless.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Types_of_Threads\"><\/span>Types of Threads<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Programs that use threads can often be divided into the following levels of difficulty:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Threads that are unrelated to each other&nbsp;<em><strong>(Easiest)<\/strong><\/em><\/li><li>Threads that are related to each other, but do not need to be synchronized<\/li><li>Threads that are related to each other, and need to be synchronized<\/li><li>Communicating, synchronized threads&nbsp;<em><strong>(Hardest)<\/strong><\/em><\/li><\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Here, we&#8217;ll discuss only the first two (simplest) types. The last two (harder) types we&#8217;ll discuss later.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Unrelated_Threads\"><\/span>Unrelated Threads<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example of a set of unrelated threads:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage threads;\n\npublic class LanguageBigots\n{\n    public static void main(String&#x5B;] args)\n    {\n        new Thread( new COBOL() ).start();\n        new Thread( new CPlusPlus() ).start();\n        new Thread( new FORTRAN() ).start();\n        new Thread( new Pascal() ).start();\n        new Thread( new Java() ).start();\n    }\n}\n\nabstract class ProgrammingLanguage implements Runnable\n{\n    public void run()\n    {\n        for (int i = 0; i &lt; 5; i++)\n        {\n            opinion();\n            Thread.currentThread().yield();\n        }\n    }\n    \n    abstract protected void opinion();\n}\n\nclass COBOL extends ProgrammingLanguage\n{\n    protected final void opinion()\n    {\n        System.out.println(&quot;COBOL: WE HAVE THE MOST LINES OF CODE! (ALL IN UPPER CASE)&quot;);\n    }\n}\n\nclass CPlusPlus extends ProgrammingLanguage\n{\n    protected final void opinion()\n    {\n        System.out.println(&quot;C++: Bjarne Stroustrup rules!&quot;);\n    }\n}\n\nclass FORTRAN extends ProgrammingLanguage\n{\n    protected final void opinion()\n    {\n        System.out.println(&quot;FORTRAN: Can *you* CONTINUE from a DO loop?&quot;);\n    }\n}\n\nclass Pascal extends ProgrammingLanguage\n{\n    protected final void opinion()\n    {\n        System.out.println(&quot;Pascal: Niklaus Wirth could teach you a lot!&quot;);\n    }\n}\n\nclass Java extends ProgrammingLanguage\n{\n    protected final void opinion()\n    {\n        System.out.println(&quot;Java: Write once, run (er, test) everywhere!&quot;);\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Notice that the threads are unrelated, even though they have code that is shared.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">One run of this program produced the following output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>COBOL: WE HAVE THE MOST LINES OF CODE! (ALL IN UPPER CASE)\nCOBOL: WE HAVE THE MOST LINES OF CODE! (ALL IN UPPER CASE)\nC++: Bjarne Stroustrup rules!\nCOBOL: WE HAVE THE MOST LINES OF CODE! (ALL IN UPPER CASE)\nC++: Bjarne Stroustrup rules!\nCOBOL: WE HAVE THE MOST LINES OF CODE! (ALL IN UPPER CASE)\nC++: Bjarne Stroustrup rules!\nCOBOL: WE HAVE THE MOST LINES OF CODE! (ALL IN UPPER CASE)\nC++: Bjarne Stroustrup rules!\nC++: Bjarne Stroustrup rules!\nFORTRAN: Can *you* CONTINUE from a DO loop?\nFORTRAN: Can *you* CONTINUE from a DO loop?\nFORTRAN: Can *you* CONTINUE from a DO loop?\nFORTRAN: Can *you* CONTINUE from a DO loop?\nFORTRAN: Can *you* CONTINUE from a DO loop?\nPascal: Niklaus Wirth could teach you a lot!\nJava: Write once, run (er, test) everywhere!\nPascal: Niklaus Wirth could teach you a lot!\nJava: Write once, run (er, test) everywhere!\nPascal: Niklaus Wirth could teach you a lot!\nJava: Write once, run (er, test) everywhere!\nPascal: Niklaus Wirth could teach you a lot!\nJava: Write once, run (er, test) everywhere!\nPascal: Niklaus Wirth could teach you a lot!\nJava: Write once, run (er, test) everywhere!<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The output would typically vary from run to run, because of the inherent non-deterministic behavior of multi-threaded programs.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Related_but_Unsynchronized_Threads\"><\/span>Related but Unsynchronized Threads<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Often a problem can be partitioned into smaller, independent, pieces, and worked on simultaneously using a set of related threads. Some examples of this kind of thread might be:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Breaking up a computational problem into smaller, concurrently executing, units<\/li><li>A set of &#8220;<em>worker threads<\/em>&#8220;, perhaps dynamically started on demand, to perform overlapping work. For example:<ul><li>Spawning a new thread to peform work on a new socket connection on a server (see Networking, later in the course)<\/li><li>Keeping around a set of threads available to do work, and assigning the work to an available thread on demand.<\/li><\/ul><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example of <em>partitioning a problem<\/em> &#8212; the problem of determining the factors of a specified number. We&#8217;ll start up a separate thread to test for factors within a particular range of numbers, and use as many threads as we need to obtain all the factors.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage threads;\n\npublic class FindFactors\n{\n  public static void main(String&#x5B;] args)\n  {\n    long number = Long.parseLong(args&#x5B;0]);\n    TestRange.setNumber(number);\n    \n    System.err.println(&quot;Finding the factors of &quot; + number);\n    \n    \/\/ Determine the number of threads to start up,\n    \/\/ one for each RANGE of divisors to test for.\n    int threadCount = (int)(number\/RANGE) + 1;\n    \n    long from = 0, to = RANGE - 1;\n    for (int thread = 0; thread &lt; threadCount; thread++)\n    {\n      new TestRange(from, to).start();\n      from += RANGE;\n      to += RANGE;\n    }\n  }\n  \n  private static final int RANGE = 100;\n}\n\nclass TestRange extends Thread\n{\n  public TestRange(long from, long to)\n  {\n    if (from == 0)\n      m_from = 2;\n    else\n      m_from = from;\n    m_to = to;\n    \n    \/\/ Set the thread name to something self-describing\n    setName(&quot;Factor (&quot; + m_from + &quot; - &quot; + m_to + &quot;)&quot;);\n  }\n  \n  public void run()\n  {\n    System.err.println(&quot;Starting thread &#039;&quot; + this.getName() + &quot;&#039;&quot;);\n    int count = 0;\n    for (long div = m_from; div &lt;= m_to &amp;&amp; div &lt; m_number; div++)\n    {\n      if (m_number % div == 0)  \/\/ Exactly divisible?\n      {\n        System.err.println(&quot;Factor &quot; + div +\n            &quot; found by thread &#039;&quot; + getName() + &quot;&#039;&quot;);\n        count++;\n      }\n      yield();\n    }\n    System.err.println(&quot;Thread &#039;&quot; + this.getName() +\n        &quot;&#039; ending (found &quot; + count + &quot; factors)&quot;);\n  }\n  \n  public static void setNumber(long number)\n  {\n    m_number = number;\n  }\n  \n  \/\/\/\/\/ Private data \/\/\/\/\/\/\/\n  \n  private static long m_number;   \/\/ All TestRange threads share this\n  private long m_from, m_to;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">When supplied with an input parameter of 456, a typical run of this program will output something like:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Finding the factors of 456\nStarting thread 'Factor (2 - 99)'\nFactor 2 found by thread 'Factor (2 - 99)'\nStarting thread 'Factor (100 - 199)'\nStarting thread 'Factor (200 - 299)'\nFactor 3 found by thread 'Factor (2 - 99)'\nStarting thread 'Factor (300 - 399)'\nStarting thread 'Factor (400 - 499)'\nFactor 4 found by thread 'Factor (2 - 99)'\nFactor 6 found by thread 'Factor (2 - 99)'\nFactor 8 found by thread 'Factor (2 - 99)'\nFactor 12 found by thread 'Factor (2 - 99)'\nFactor 114 found by thread 'Factor (100 - 199)'\nFactor 19 found by thread 'Factor (2 - 99)'\nFactor 228 found by thread 'Factor (200 - 299)'\nThread 'Factor (400 - 499)' ending (found 0 factors)\nThread 'Factor (300 - 399)' ending (found 0 factors)\nFactor 24 found by thread 'Factor (2 - 99)'\nFactor 152 found by thread 'Factor (100 - 199)'\nThread 'Factor (200 - 299)' ending (found 1 factors)\nFactor 38 found by thread 'Factor (2 - 99)'\nThread 'Factor (100 - 199)' ending (found 2 factors)\nFactor 57 found by thread 'Factor (2 - 99)'\nFactor 76 found by thread 'Factor (2 - 99)'\nThread 'Factor (2 - 99)' ending (found 11 factors)<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In the above example, while the threads do share data (the number under test), they only need to read that number. They do not need to change it.&nbsp; Consequently, there is no synchronization problem.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Threads are very important in Java, especially when it comes to GUI programming.&nbsp; Every Java program has at least two threads;&nbsp; every Java GUI program has at least three threads. What is Multithreading? Multithreading is the ability to do (or appear to do) more than one thing at a time. Every Java program is multithreaded, [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"parent":19,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_eb_attr":"","ocean_front_end_style_editor":"no","ocean_post_layout":"left-sidebar","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"ocs-course-topics-sidebar","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","footnotes":""},"class_list":["post-252","page","type-page","status-publish","hentry","entry"],"_links":{"self":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/252","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/comments?post=252"}],"version-history":[{"count":18,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/252\/revisions"}],"predecessor-version":[{"id":360,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/252\/revisions\/360"}],"up":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/19"}],"wp:attachment":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/media?parent=252"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}