Java線程

創建線程的方法

繼承Thread

public class Client {
    public static void main(String[] args) {
        MyThread myThread = new MyThread("線程1");
        myThread.start();
    }
}

class MyThread extends Thread {

    public MyThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        System.out.println(this.getName() + "正在運行...");
    }
}

實現Runnable接口

public class Client {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.setName("線程1");
        thread.start();
    }
}

class MyRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "正在運行...");
    }
}

匿名內部類

public class Client {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "正在運行...");
            }
        });
        thread.setName("線程1");
        thread.start();
    }
}

線程睡眠

/**
* 睡眠
* @Param 睡眠時間 單位ms
*/
Thread.sleep(1000);

線程睡眠時間要適度!

線程參與

public class Client {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 100; i++) {
                    System.out.println(Thread.currentThread().getName()
                            + "執行第" + i + "次");
                }
            }
        });
        System.out.println("主線程運行1");
        thread.start();
        // 參與1ms
        thread.join(1);
        System.out.println("主線程運行2");
    }
}

在這裏插入圖片描述

線程優先級

設定線程優先級僅僅在線程調度中有作用,並不意味着優先級高的線程先運行,僅僅說明在線程調度中有優先權;
Java中線程優先級範圍爲1~10的正整數,並有三個常量
Thread.MIN_PRIORITY   // 值爲1
Thread.MAX_PRIORITY   // 值爲10
Thread.NORM_PRIORITY  // 值爲5 線程默認值

線程同步

使用synchronized關鍵字可實現線程同步,可保證一個資源不被同時訪問
synchronized關鍵字可修飾成員方法、靜態方法、代碼塊。
  • 修飾成員方法
private synchronized void getSalary(){
	// 方法體
}
  • 修飾靜態方法
private synchronized static void getSalary(){
	// 方法體
}
  • 修飾代碼塊
synchronized(this) {
	// 代碼塊
}

範例:賬戶存取

線程通信

wait()  
線程等待
notify() 
喚醒一個正在等待的線程,此喚醒具有任意性。
notifyAll() 
喚醒所有正在等待的線程。

範例:生產者消費者問題

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章