⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 demo2.java

📁 Write a Java program that demonstrates a high priority thread using sleep to give lower priority thr
💻 JAVA
字号:
package sleep;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 1.0
 */
// Exercise 15.21 Solution: Demo2.java
// Program demonstrates high priority threads

// Java core packages
import java.awt.*;
import java.awt.event.*;

// Java extension packages
import javax.swing.*;

public class Demo2 extends JFrame {
   private HighThread high;
   private LowThread low;
   private JTextArea output;

   // Demo2 constructor
   public Demo2()
   {
      super( "Demo2" );

      // set up GUI
      output = new JTextArea( 10, 20 );
      getContentPane().add( output );
      setSize( 250, 200 );
      setVisible(true);

      // initialize threads
      high = new HighThread( output );
      low = new LowThread( output );

      // start threads
      high.start();
      low.start();
   }

   // execute application
   public static void main( String args[] )
   {
      Demo2 application = new Demo2();

      application.setDefaultCloseOperation(
         JFrame.EXIT_ON_CLOSE );
   }

} // end class Demo2

// subclass of Thread
class HighThread extends Thread {
   private JTextArea display;

   // HighThread constructor
   public HighThread( JTextArea textArea )
   {
      display = textArea;
      setPriority( Thread.MAX_PRIORITY );
   }

   // action to perform on execution
   public void run()
   {
      for ( int x = 0; x < 5; x++ ) {
         try {
            sleep( 100 );
         }

         // process exception from sleep
         catch ( Exception exception ) {
            JOptionPane.showMessageDialog( null,
               exception.toString(), "Exception",
                  JOptionPane.ERROR_MESSAGE );
         }

         display.append( "High Priority Thread\n" );
      }
   }

}  // end class HighThread

// subclass of Thread
class LowThread extends Thread {
   private JTextArea display;

   // LowThread constructor
   public LowThread( JTextArea textArea )
   {
      display = textArea;
      setPriority( Thread.MIN_PRIORITY );
   }

   // action to perform on execution
   public void run()
   {
      for ( int y = 0; y < 5; y++ )
         display.append( "Low Priority Thread\n" );
   }

}  // end class LowThread

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -