java线程入门一

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java线程入门一相关的知识,希望对你有一定的参考价值。

线程优先级:

在JAVA线程中,通过一个int型变量priority来控制线程优先级,线程的有限机为1-10,默认为5,优先级高的线程获得的运行时间要高于优先级低的线程。但这只是一个提示,操作系统和JVM可能会根据自身情况忽略这个情况。请看下面代码:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Priority {
    private static volatile boolean notStart=true;
    private static volatile boolean notEnd=true;

    public static void main(String[] args) throws Exception{
        List<Job> jobs=new ArrayList<>();
        for(int i=0;i<10;++i){
            int priority=i<5?Thread.MIN_PRIORITY:Thread.MAX_PRIORITY;
            Job job=new Job(priority);
            jobs.add(job);
            Thread thread=new Thread(job,"Thread"+i);
            thread.setPriority(priority);
            thread.start();
            //thread.setPriority(188);  优先级超出1-10,这个范围时,运行期会抛异常;
        }
        notStart=false;
        TimeUnit.SECONDS.sleep(10);
        notEnd=false;
        for(Job job:jobs){
            System.out.println("Job Priority:"+job.priority+",Conut:"+job.jobCount);
        }

    }

 private  static class Job implements Runnable{
        private int priority;
        private long jobCount;                                               

     public Job(int priority) {
         this.priority = priority;
     }

     public void run() {                                           
         while(notStart){
             Thread.yield();
         }
         while (notEnd){
             Thread.yield();
             jobCount++;
         }
     }                     
 }

执行结果如下:

Job Priority:1,Conut:4665639
Job Priority:1,Conut:4814788
Job Priority:1,Conut:4783102
Job Priority:1,Conut:5667441
Job Priority:1,Conut:4688465
Job Priority:10,Conut:4618501
Job Priority:10,Conut:5598076
Job Priority:10,Conut:5212791
Job Priority:10,Conut:5627112
Job Priority:10,Conut:4332899

线程状态:

 










以上是关于java线程入门一的主要内容,如果未能解决你的问题,请参考以下文章

算法竞赛入门码蹄集进阶塔335题(MT3330-3335)

译丨Yarn - Javascript 新一代套件管理

Java多线程入门中几个常用的方法

Java入门

反射机制入门

反射机制入门