我们来看一下Thread类 线程类
这个类他实现来Runnable 接口 实现的run()方法
我们来看一下创建线程常用的几种方式
-
第一种 创建一个类继承 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()); } }
-
第二种 创建一个类实现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("我是子业务"); } }
-
第三种比较特殊 有返回值的task FutureTask() 关于这种方式 会在后面并发包里面来说明这个方式
一些常用的方法
-
线程设置优先级
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) 通过这个方法可以给线程设置优先级
-
public static native Thread currentThread()获取当前线程对象
public static native Thread currentThread(); 获取当前线程对象
- public static native void yield()线程 让出cpu执行权
public static native void yield(); 调用该方法 线程 让出cpu执行权 可以说是 从运行状态--> 到就绪状态 但是该方法不一定能成功 因为 让出执行权的线程 可能再次抢到线程的执行权
-
public static native void sleep(long millis)
public static native void sleep(long millis) 调用该方法 线程会进入等待状态 等时间一到 又会进入就绪状态
-
public synchronized void start()
public synchronized void start() start()方法的具体流程: start(判断当前线程是不是首次创建, Java方法)->调用start0()方法(JVM)->通过JVM进行资源调度, 系统分配->回调run()方法(Java方法)执行线程的具体操作任务。
-
public void interrupt()
public void interrupt() 可以通过抛出异常机制 提前打断睡眠
-
public final void join() throws InterruptedException
public final void join() throws InterruptedException “线程合并” 当前线程join 到现在的线程中 等待此线程执行结束后 再继续执行