1. 程式人生 > >深度解析線程工作原理

深度解析線程工作原理

路徑 cep dead test deadlock end priority interrupt prior

  1, 線程的概念
    一個程序中的方法有幾條執行路徑, 就有幾個線程

  2, 線程的創建

    兩種方式:

      1, 繼承Thread

        class TestThread extends Thread {......}

      2, 實現Runnable接口, 然後作為參數傳入到Thread類的構造方法中

        class TestThread implements Runnable {......}

    線程的啟動:

    調用線程類中的start()方法, 不能直接調用run()方法, 直接調用run()方法那叫方法調用, 不是啟動線程

  3, 線程常用方法

    isAlive()

      判斷線程是否還活著, 調用start()之前和終止之後都是死的, 其他的都是活的

    interrupt()

      停止線程

    getPriority()

    setPriority(int i)

    設置優先級, 優先級的概念: 誰的優先級高, 誰執行的時間就多

    Thread裏面的默認優先級:

      Thread.MIN_PRIORITY = 1

      Thread.MAX_PRIORITY = 10

      Thread.NORM_PRIORITY = 5

    Thread.sleep(1000); 將程序暫定一會

    join() 合並線程

    yield() 讓出CPU執行其他線程

  4, 線程同步

    synchronized

  線程同步解析:

package com.maya.sync.deadlock;

public class TestPractise implements Runnable {

    private int b = 100;
    
    public synchronized void m1() {
        b = 1000;
        try {
            Thread.sleep(
2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("m1: " + b); } public synchronized void m2() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } b = 2000; } public void run() { m1(); } public static void main(String[] args) { TestPractise tp = new TestPractise(); Thread t = new Thread(tp); t.start(); tp.m2(); // 兩個方法都修改了同一個值, 這兩個方法都應該加上synchronized System.out.println("main: " + tp.b); } /* 先執行m2,再執行m1 * 一條記錄, 加鎖是應該加在改的方法上還是讀的方法上 */ }

深度解析線程工作原理