SoFunction
Updated on 2025-03-08

Java thread priority sample code


import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

/**
* Priority of threads
* The 10 counter threads are set to different priority levels. We observe the role of priority through the accumulation of counters.
* @author Five Dogs of Rice
 * @blog /mq612
 */
public class TestMain extends JFrame {
private MyThread [] thread = null; // thread to operate
    private JPanel pane = null;
private JButton startButton = null, stopButton = null; // Start and end buttons

    public TestMain(){
super("thread priority");
        pane = new JPanel();
        thread = new MyThread[10];
for(int i = 0; i < 10; i++){ // The minimum priority of the thread is 1 and the maximum is 10
            thread[i] = new MyThread(i + 1);
        }
startButton = new JButton("Execution");
        (new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                for(int i = 0; i < 10; i++){
                    thread[i].start();
                }
            }
        });
stopButton = new JButton("end");
        (new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                for(int i = 0; i < 10; i++){
                    thread[i].quit();
                }
            }
        });
        JPanel p = new JPanel();
        (startButton);
        (stopButton);
        ().add(pane);
        ().add(p, );
        (JFrame.EXIT_ON_CLOSE);
        (500, 300);
        (null);
        (true);
    }
    /**
* Counter thread
     */
    class MyThread extends Thread{
private JTextField text = null; // Counter
private int i = 0; // Counter
private int priority = 0; // priority
private JLabel label = null; // Priority display label
private boolean b = true; // Control the boolean variable ending at the thread

        public MyThread(int priority){
            = priority;
            (priority);
            JPanel p = new JPanel();
            label = new JLabel("Priority=" + priority);
            text = new JTextField(12);
            (label);
            (text);
(p); // Add your counter to the main window panel
        }
        /**
* End thread
         */
        public void quit(){
            b = false;
        }
        public void run(){
            while(b){
                ((i++));
                try {
(1); // Reducing the number of milliseconds here makes it easier for us to observe the results
                } catch (InterruptedException ex) {
                    ();
                }
            }
        }
    }

    public static void main(String [] args){
        new TestMain();
    }