JAVA多线程——线程及相关方法

在这里插入图片描述

线程的开辟

1.继承方式

/**
 * 将自定义的继承自Thread类的线程类实例化
 * 需要调用start()方法使线程启动,而非直接使用run()
 * start()会开启一个新的线程,来执行run()中逻辑
 * 若直接调用run(),则线程将无法进入就绪态
*/
public class ThreadCreate {
    public static void main(String[] args){
        MyThread mt = new MyThread();
        mt.start();
        System.out.println("主线程逻辑执行结束");
    }
}

/**
 * 自定义的线程类
 * 需要重写run()方法,将需要并发的任务写到run()方法中
 */
class MyThread extends Thread{
    @Override
    public void run(){
        for(int i=0;i<10;i++){
            System.out.println("子线程中的逻辑"+i);
        }
    }

}

2.Runnable接口方式

public class ThreadCreate {
    public static void main(String[] args){
        Runnable r =()->{
            for(int i=0;i<10;i++){
                System.out.println("子线程中的逻辑"+i);
            }
        };

        Thread t = new Thread(r);
        t.start();
        System.out.println("主线程逻辑执行结束");
    }
}

线程的休眠

class MyThread extends Thread{
    @Override
    public void run(){
        for(int i=0;i<10;i++){
            System.out.println("子线程中的逻辑"+i);
            
            //线程休眠,参数是以毫秒为单位的时间差
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

线程的优先级

public class ThreadMethod {
    public static void main(String[] args) {
        threadPriority();
    }

    private static void threadPriority(){
        //设置线程的优先级,只是修改线程抢夺CPU时间片的概率
        //并不是优先级高的线程一定能抢到CPU时间片
        //优先级设置参数是一个[0,10)的整数,不设置时默认是5
        Runnable r = ()->{
            for(int i=0;i<100;i++){
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        };

        Thread t1= new Thread(r,"Thread-1");
        Thread t2= new Thread(r,"Thread-2");

        t1.setPriority(10);
        t2.setPriority(1);

        t1.start();
        t2.start();

    }
}

线程的礼让

/**线程礼让,指让当前处于运行状态的线程释放CPU资源,回到就绪态。
*/
private static void threadYield(){
        Runnable r = new Runnable() {
            @Override
            public void run() {
                for(int i=0;i<10;i++){
                    System.out.println(Thread.currentThread().getName()+":"+i);
                    if(i==3)
                        Thread.yield();
                }
            }
        };

        Thread t1 = new Thread(r,"Thread-1");
    	Thread t2 = new Thread(r,"Thread-2");

        t1.start();
        t2.start();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值