Thread类

我们来看一下Thread类 线程类
这个类他实现来Runnable 接口 实现的run()方法
我们来看一下创建线程常用的几种方式
  1. 第一种
     创建一个类继承 Thread类 并重写run()方法  run方法中写这个线程要做的事情 
    public class MyThreadTest {
        public static void main(String[] args) {
            //创建该线程
            MyThread myThread = new MyThread();
    
            //启动该线程
            //这个start的作用就是给这个线程分配新的栈空间 把run()方法压栈  这个方法一瞬间就执行结束了
            myThread.start();
            //主线程
            System.out.println("我是主线程");
    
    
        }
    }
    //线程类
    class MyThread extends Thread{
        @Override
        public void run() {
            //在这里写需要该线程做的事情
            System.out.println("我是子线程");
    
            System.out.println(Thread.currentThread());
        }
    }

  2. 第二种
    创建一个类实现Runnable接口 实现run()方法
    public class MyThreadTest2 {
        public static void main(String[] args) {
            //创建该线程
            MyThread2 myThread2 = new MyThread2();
            Thread thread2 = new Thread(myThread2);
            //也可以写成  Thread thread2 = new Thread(new MyThread2());
    
            //线程启动
            thread2.run();
        }
    }
    //线程类
    class MyThread2 implements Runnable{
        @Override
        public void run() {
            System.out.println("我是子业务");
        }
    }

  3. 第三种比较特殊 有返回值的task
     FutureTask()
     关于这种方式  会在后面并发包里面来说明这个方式

一些常用的方法

  1. 线程设置优先级
         public final static int MIN_PRIORITY = 1;
    
    
         public final static int NORM_PRIORITY = 5;
    
    
         public final static int MAX_PRIORITY = 10;
    
         线程有抢占优先级   最低是1  最高是10  默认是5
    
         public final void setPriority(int newPriority)
         通过这个方法可以给线程设置优先级

  2. public static native Thread currentThread()获取当前线程对象
     public static native Thread currentThread();
                    获取当前线程对象

  3. public static native void yield()线程 让出cpu执行权
    public static native void yield();
     调用该方法  线程 让出cpu执行权
      可以说是  从运行状态-->  到就绪状态
       但是该方法不一定能成功  因为 让出执行权的线程 可能再次抢到线程的执行权
  4. public static native void sleep(long millis)
    public static native void sleep(long millis)
                    调用该方法  线程会进入等待状态
                    等时间一到  又会进入就绪状态

  5. public synchronized void start()
    public synchronized void start()
    
    start()方法的具体流程:
    start(判断当前线程是不是首次创建,
    Java方法)->调用start0()方法(JVM)->通过JVM进行资源调度,
    系统分配->回调run()方法(Java方法)执行线程的具体操作任务。

  6. public void interrupt()
     public void interrupt()
     可以通过抛出异常机制  提前打断睡眠

  7. public final void join() throws InterruptedException
     public final void join() throws InterruptedException
    
      “线程合并”  当前线程join 到现在的线程中 等待此线程执行结束后  再继续执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值