【JAVA】Java 线程

java 线程

一、线程状态

  • 1、new: 线程使用new方法创建之后 调用start()方法之前
  • 2、runnable: 线程调用start() 方法之后
  • 3、non-runnable: 线程被挂起或发生阻塞而产生的状态,例如
    • 线程调用sleep()
    • 线程调用wait() ps. 再次调用notify()/notifyAll()才能回到可运行状态
    • 线程suspend ps. resume 恢复
    • 阻塞IO
  • 4、done: 线程调用stop() 方法后,线程 run()方法完成后

二、线程优先级

优先级高的线程先抢占cpu并得以执行,所获得的cpu时间片也多,执行效率高,执行速度快

// newPriority 只能取值1-10 数字越低优先级越高
public final void setPriority(int newPriority)

三、synchornized 关键字使用

// 1、同步方法
class 类名{
    public synchornized 返回值 方法名(){}
}
// 2、同步对象
synchornized (obj){}

四、锁

  • 1、死锁: 两个小孩打架 谁也不让谁

五、线程方法详解

  • 1、join()
     // main 相当于主线程
    // 子线程调用join()方法后,主线程会一直等待子线程的完成
    public static void main(String[] args) throws InterruptedException {

        ChildThread childThread = new ChildThread();
        childThread.start();
        childThread.join();

        System.out.printf("%s 主线程结束 
",Thread.currentThread().getName());

    }


    // 子线程
    static class ChildThread extends Thread {
        public void run() {
            try {
                Thread.sleep(5*1000);
                System.out.printf("%s 子线程结束 
",Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
“年轻时,我没受过多少系统教育,但什么书都读。读得最多的是诗,包括烂诗,我坚信烂诗早晚会让我邂逅好诗。” by. 马尔克斯
原文地址:https://www.cnblogs.com/jzsg/p/10888365.html