当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ThreadGroup setMaxPriority()用法及代码示例


ThreadGroup类setMaxPriority()方法

  • setMaxPriority() 方法在 java.lang 包中可用。
  • setMaxPriority() 方法用于分配此线程组的最大优先级,对已存在于此线程组中的更高优先级线程没有影响。
  • setMaxPriority() 方法是一个非静态方法,它只能通过类对象访问,如果我们尝试使用类名访问方法,那么我们将得到一个错误。
  • setMaxPriority() 方法可能会在分配此 ThreadGroup 的优先级时抛出异常。
    SecurityException- 当前线程不允许更新此线程组时,可能会抛出此异常。

用法:

    public final void setMaxPriority(int prior);

参数:

  • int prior- 代表这个线程组的新优先级。

返回值:

这个方法的返回类型是void- 它什么都不返回。

例:

// Java program to demonstrate the example 
// of void setMaxPriority(int prior) method of ThreadGroup 

public class SetMaxPriority implements Runnable {
    public static void main(String[] args) {
        SetMaxPriority max_pri = new SetMaxPriority();
        max_pri.setPrio();
    }

    public void setPrio() {
        try {
            // Create two thread group and the named are base
            // and derived
            ThreadGroup base = new ThreadGroup("Base ThreadGroup");
            ThreadGroup derived = new ThreadGroup(base, "Derived ThreadGroup");

            // By using setMaxPriority() method is to set the
            // maximum priority for both the thread group
            // 7 for base and 5 for derived thread group

            base.setMaxPriority(7);
            derived.setMaxPriority(5);

            // create two threads
            Thread th1 = new Thread(base, this);
            Thread th2 = new Thread(derived, this);

            //By using getName() method is to retrieve the
            // name of the thread th1
            System.out.println(th1.getName() + " " + "begins.....");

            // By using start() method is to start its execution 
            // of thread th1
            th1.start();

            // By using getName() method is to retrieve the
            // name of the thread th2
            System.out.println(th2.getName() + " " + "begins.....");
            th2.setPriority(10);

            // By using start() method is to start its execution 
            // of thread th2
            th2.start();

            // By using join() method is to wait the current
            // thread till complete execution of another
            // thread
            th1.join();
            th2.join();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    // Override run()
    public void run() {
        for (int k = 0; k < 100; ++k)
            ++k;
        System.out.println(Thread.currentThread().getName() + " " + "ends.....");
    }
}

输出

Thread-0 begins.....
Thread-0 ends.....
Thread-1 begins.....
Thread-1 ends.....


相关用法


注:本文由纯净天空筛选整理自Preeti Jain大神的英文原创作品 Java ThreadGroup setMaxPriority() method with example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。