首页 > 编程语言 > 详细

java多线程技术

时间:2019-11-17 21:50:57      阅读:72      评论:0      收藏:0      [点我收藏+]

如何实现线程

首先实现线程的两个方法:
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。

技术分享图片

 

 

 

java多线程技术

原文:https://www.cnblogs.com/endust/p/11878214.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!