Java多线程 - 线程优先级 [英] Java multithreading - thread priority

查看:177
本文介绍了Java多线程 - 线程优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释线程优先级在java中的工作原理。这里的困惑是,如果java根据其优先级不保证 Thread 的实现,那么为什么这个 setpriority()用于的函数。

Can anybody explain how thread priority works in java. The confusion here is if java does'nt guarantee the implementation of the Thread according to its priority then why is this setpriority() function used for.

我的代码如下:

public class ThreadSynchronization implements Runnable{

    public synchronized void run() {
        System.out.println("Starting Implementation of Thread "+Thread.currentThread().getName());
        for(int i=0;i<10;i++)
        {
            System.out.println("Thread "+Thread.currentThread().getName()+" value : "+i);
        }
        System.out.println("Ending Implementation of Thread "+Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        System.out.println("Program starts...");
        ThreadSynchronization th1 = new ThreadSynchronization();
        Thread t1 = new Thread(th1);
        t1.setPriority(1);
        synchronized(t1)
        {
            t1.start();
        }

        ThreadSynchronization th2 = new ThreadSynchronization();
        Thread t2 = new Thread(th2);
        t2.setPriority(9);
        synchronized (t2) {
            t2.start(); 
        }

        System.out.println("Program ends...");
    }
}

在上述程序中,即使我更改优先级I找不到输出的差异。
另外,如何使用线程优先级的实时应用程序将会有很大帮助。
谢谢。

In the above program even if I change the priority I find no difference in the output. Also a real time application of how thread priority can be used would be of great help. Thanks.

推荐答案

线程优先级只是对OS任务调度程序的一个提示,并且依赖于底层操作系统。操作系统将尝试为高优先级线程分配更多资源,但不保证。因此,如果您的程序依赖于线程优先级而不是您将程序绑定到底层操作系统,这是不好的。

Thread priority is just a hint to OS task scheduler and is dependent on the underlying OS. OS will try to allocate more resources to a high priority thread but it does not guarantee it. So if your program is dependent on thread priorities than you are in-turn binding your program to underlying OS, which is bad.

来自 实践中的Java并发

From Java Concurrency in Practice:


避免使用线程优先级的诱惑,因为它们增加了
平台依赖性并且可能导致活跃性问题。大多数并发
应用程序可以使用所有线程的默认优先级。

Avoid the temptation to use thread priorities, since they increase platform dependence and can cause liveness problems. Most concurrent applications can use the default priority for all threads.

这篇关于Java多线程 - 线程优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆