zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java线程优先级示例代码

JAVA线程代码 示例 优先级
2023-06-13 09:15:05 时间

使用过Bit下载软件的同学应该很清楚,我们有多个下载任务同时执行,而其中的某一个或多个是非常重要的,于是给这些任务设定一个高度优先,以便任务可以获取更多的带宽尽早完成下载。Java线程的优先级也差不多,优先级越高排程器就会给它越多的CPU执行时间,但请注意:如果有多个线程在等待一个机锁的时候,并不是优先级越高就可以越早执行。

复制代码代码如下:


importjava.awt.BorderLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JPanel;
importjavax.swing.JTextField;

/**
 *线程的优先级
 *10个计数器线程分别被设置了不同的优先级,我们通过计数器的累加来观察优先级的作用
 *@author五斗米
 *@bloghttp://blog.csdn.net/mq612
 */
publicclassTestMainextendsJFrame{
   privateMyThread[]thread=null;//要操作的线程
   privateJPanelpane=null;
   privateJButtonstartButton=null,stopButton=null;//启动、结束按钮

   publicTestMain(){
       super("线程的优先级");
       pane=newJPanel();
       thread=newMyThread[10];
       for(inti=0;i<10;i++){//线程的优先级最小是1,最大是10
           thread[i]=newMyThread(i+1);
       }
       startButton=newJButton("执行");
       startButton.addActionListener(newActionListener(){
           publicvoidactionPerformed(ActionEvente){
               for(inti=0;i<10;i++){
                   thread[i].start();
               }
           }
       });
       stopButton=newJButton("结束");
       stopButton.addActionListener(newActionListener(){
           publicvoidactionPerformed(ActionEvente){
               for(inti=0;i<10;i++){
                   thread[i].quit();
               }
           }
       });
       JPanelp=newJPanel();
       p.add(startButton);
       p.add(stopButton);
       this.getContentPane().add(pane);
       this.getContentPane().add(p,BorderLayout.NORTH);
       this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       this.setSize(500,300);
       this.setLocationRelativeTo(null);
       this.setVisible(true);
   }
   /**
    *计数器线程
    */
   classMyThreadextendsThread{
       privateJTextFieldtext=null;//计数器
       privateinti=0;//计数器
       privateintpriority=0;//优先级
       privateJLabellabel=null;//优先级显示标签
       privatebooleanb=true;//控制线程结束的boolean变量

       publicMyThread(intpriority){
           this.priority=priority;
           this.setPriority(priority);
           JPanelp=newJPanel();
           label=newJLabel("Priority="+priority);
           text=newJTextField(12);
           p.add(label);
           p.add(text);
           pane.add(p);//将自己的计数器加入主窗口面板中
       }
       /**
        *结束线程
        */
       publicvoidquit(){
           b=false;
       }
       publicvoidrun(){
           while(b){
               this.text.setText(Integer.toString(i++));
               try{
                   this.sleep(1);//减小这里的毫秒数,可以让我们更容易观察到结果
               }catch(InterruptedExceptionex){
                   ex.printStackTrace();
               }
           }
       }
   }

   publicstaticvoidmain(String[]args){
       newTestMain();
   }