zoukankan      html  css  js  c++  java
  • java多线程技术

    如何实现线程

    首先实现线程的两个方法:
    1、继承thread;
    2、实现接口Runnable类;

    这边我就说一下第二种,因此第二种在开发中使用的比较多一些,能避免继承还是少避免继承。

    RunnableDemo.java:

    class RunnableDemo implements Runnable{
        public void run(){
            for(int i=0;i<100;i++){
                System.out.println("Runnable -->"+i);
            }
        }
    }

    Test.java:

    class Test{
        public static void main(String[] args){
            RunnableDemo r = new RunnableDemo();
            Thread t = new Thread(r);
            t.start();
            
        }
    }

    运行结果:

    控制线程的方法

    中断线程

    Thread.sleep()

    需要添加异常处理,比如修改RunnableDemo.java:

    class RunnableDemo implements Runnable{
        public void run(){
            for(int i=0;i<100;i++){
                System.out.println("Runnable -->"+i);
                if(i == 50){
                    try{
                        Thread.sleep(2000);
                    }
                    catch(Exception e){
                        System.out.println(e);
                    }
                    
    
                }
            }
        }
    }

    运行后会在i等于50的时候睡眠2秒。


    Thread.yield()

    设置线程的优先级

    Thread.getPriority()

    作用:取得优先级

    class Test{
        public static void main(String[] args){
            RunnableDemo r = new RunnableDemo();
            Thread t = new Thread(r);
            t.start();
            System.out.println(t.getPriority());
            
        }
    }

    从下图输出结果来看,默认优先级为5:


    Thread.setPrioority()

    作用:设置最大优先级

    class Test{
        public static void main(String[] args){
            RunnableDemo r = new RunnableDemo();
            Thread t = new Thread(r);
            t.start();
            t.setPriority(Thread.MAX_PRIORITY);
            System.out.println(t.getPriority());
            
        }
    }

    输出结果为10,说明最大优先级为10。

  • 相关阅读:
    二叉树的序列化与反序列化
    寻找重复的子树
    [ABC216H] Random Robots
    Codeforces Round #741 (Div. 2)
    [Gym 102798K] Tree Tweaking
    CF798E Mike and code of a permutation
    CF1149E Election Promises
    [BZOJ 4311] 向量
    CF1268D Invertation in Tournament
    [做题笔记] 浅谈势能线段树在特殊区间问题上的应用
  • 原文地址:https://www.cnblogs.com/endust/p/11878214.html
Copyright © 2011-2022 走看看