多线程的两种创建方式(1)

本文探讨了Java中通过继承`Thread`类和实现`Runnable`接口创建线程的方式,并展示了如何设置线程优先级及并发控制。通过BaseTest和Base子类,以及BaseTest2实现Runnable的案例,展示了线程调度的基本原理。
摘要由CSDN通过智能技术生成
public class BaseTest {

    public static void main(String[] args) {
        Base base = new Base("线程一");
        base.start();
        base.setPriority(10);//设置线程优先级,最高10
        Thread.currentThread().setName("主线程");
        Thread.currentThread().setPriority(1);//最低1
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName()+i);
            }
//            if(i == 20){
//                try {
//                    base.join();//当前线程进入阻塞状态,直到执行完对象线程,再继续执行当前线程
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }
        }
    }


class Base extends Thread{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {

//            try {
//                sleep(10);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        }
    }
    public Base(String name){
        super(name);
    }
}

第一种:继承类

public class BaseTest2 implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {

            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName()+ i);
            }
        }
    }

}
class Base2{
    public static void main(String[] args) {
        BaseTest2 baseTest2 = new BaseTest2();
        Thread thread = new Thread(baseTest2);
        thread.setPriority(10);
        thread.setName("线程一");
        thread.start();

    }
}

第二种:接口

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值