10.8 多线程 底层

线程的创建和使用

Tread类

  1. 构造器
    • Thread():创建新的Thread对象
    • Thread(Runnable target):指定创建线程的目标对象,它实现了Runnable接
  2. 继承Thread类
  • 定义子类继承Thread类。
  • 子类中重写Thread类中的run方法。
  • 创建Thread子类对象,即创建了线程对象。
  • 调用线程对象start方法:启动线程,调用run方法。

Runnable接口

  • 实现Runnable接口
  • 定义子类,实现Runnable接口。
  • 子类中重写Runnable接口中的run方法。
  • 通过Thread类含参构造器创建线程对象。
  • 将Runnable接口的子类对象作为实际参数传递给Thread类的构造器中。
  • 调用Thread类的start方法:开启线程,调用Runnable子类接口的run方法。

方法

getName  获取名字
setName 设置名字
getPriority  获取 优先级
setPriority 设置优先级
sleep  睡眠
interrupt  唤醒
Thread.currentThread    获取当前的线程

public class Three_002 {
    public static void main(String[] args) {
    继承类的子线程创建
      Thread thread= new Three_022();
      thread.setName("子线程");
        try {
// 线程合并
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.start();
        Thread.currentThread().setName("main");
        for (int i = 6; i <11;i++ ) {
            System.out.println(Thread.currentThread().getName() + i);
//实现类 的子线程创建
        Thread t1=new Thread(new Test_0014());   
        t1.setName("实现类线程");
        t1.start();
        Thread.currentThread().setName("zhu");
        System.out.println("123456");

        Test_0014.setIsStop(false);


}





    }
}
class Three_022 extends Thread{
    @Override
    public void run() {
        for (int i = 1; i < 5;i++) {
            System.out.println(this.getName()+i);
}


        while (true) {
            try {
// 睡眠
                Thread.sleep(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yy,MM,dd,HH:mm:ss");
            String format = simpleDateFormat.format(new Date());
            System.out.println(getName()+"~~~~~~~~~~~~~~~~~~~~~~~"+format);
//        }



    }
}
class Test_0014 implements Runnable {
    static boolean isStop=true;
    @Override
    public void run() {

       while (true){
           if (isStop) {
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yy,MM,dd,HH:mm:ss");
               String format = simpleDateFormat.format(new Date());
               System.out.println(Thread.currentThread().getName()+ format);
           }else {
               return;
           }
           }

    }

    public static boolean isIsStop() {
        return isStop;
    }

    public static void setIsStop(boolean isStop) {
        Test_0014.isStop = isStop;
    }
}

优先级

1-10

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值