prioritydemo.java

来自「Java面向对象编程(随书配套源代码) 阐述了面向对象编程的思想」· Java 代码 · 共 61 行

JAVA
61
字号
package chapter10;
public class PriorityDemo
{
    public static void main(String args[])
    {
        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        NewThread high=new NewThread(Thread.NORM_PRIORITY+2);
        NewThread low=new NewThread(Thread.NORM_PRIORITY-2);
        low.start();
        high.start();
        try
        {
            Thread.sleep(3000);
        } 
        catch(InterruptedException e)
        {
            System.out.println("Main thread interrupted.");
        }
        low.stop();
        high.stop();
        try
        {
            high.t.join();
            low.t.join();
        }
        catch(InterruptedException e)
        {
            System.out.println("InterruptedException caught.");
        }
        System.out.println("Low-priority thread :"+low.click);
        System.out.println("High-priority thread :"+high.click);
    }
}

class NewThread implements Runnable
{
    int click=0;
    Thread t;
    private volatile boolean running=true;
    public NewThread(int p)
    {
        t=new Thread(this);
        t.setPriority(p);
    }
    public void run()
    {
        while(running)
        {
            click++;
        }
    }
    public void stop()
    {
        running=false;
    }
    public void start()
    {
        t.start();
    }
}

⌨️ 快捷键说明

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