第九章 多線程java
線程是一個程序內部的順序控制流多線程
線程和進程的區別:spa
每一個進程都有獨立的代碼和數據空間,進程間的切換會有較大的開銷操作系統
線程能夠當作是輕量級的進程,同一類線程共享代碼和數據空間,每一個線程都有獨立的運行棧和程序計數器,線程切換的開銷小線程
多進程:在操做系統中能同時運行多個任務(程序code
多線程:在同一應用程序中有多個順序流同時執行對象
線程的建立和啓動blog
第一種繼承
定義線程類實現runnable接口接口
Thread myThread = new Thread(target)//target爲Runnable接口類型
Runnable中只有一個方法:public void run();用於定義線程運行體
使用Runnable接口能夠爲多個線程提供共享的數據
在實現runnable接口的類的run方法定義中能夠使用Thread的靜態方法:
Public static Thread currentThread()獲取當前線程的引用
public class ThreadTest1 { public static void main(String arg[]) { Runner1 runner1 = new Runner1(); //runner1.run(); Thread t = new Thread(runner1) ; t.start(); for(int i = 1;i<100;i++) { System.out.println("Main said---"+i); } } } class Runner1 implements Runnable{ public void run() { for(int i = 1;i<100;i++) { System.out.println("Thread said"+i); } } }
第二種
能夠定義一個Thread的子類並重寫其run方法如:
Class Mythread extends Thread{
Public void run(){}
}
而後生成該類的對象:
MyThread myThread = new MyThread()
只要能只用接口,就不要用thread類繼承
isAlive() 判斷線程是否還活着,即線程是否還未終止
getPriority() 得到線程的優先級數值
setPriority() 設置線程的優先級數值
Thread.sleep()將當前線程睡眠指定毫秒數
join()調用某線程的該方法,將當前線程與該線程合併,即等待該線程結束,再回復當前線程的運行
yield()讓出cpu,當前線程進入就緒隊列等待調度
wait()當前線程進入對象的wait pool
notify()/notifyAll()喚醒對象的wait pool中的一個/全部等待線程
sleep方法
能夠調用Thread的靜態方法;
public static void sleep(long milis) throws InterruptedException 使得當前線程休眠
因爲是靜態方法,sleep能夠直接由類名調用: Thread.sleep(...)
join方法
合併某個線程,至關於方法調用
yield方法
讓出CPU,給其餘線程執行的機會
設置優先級:t1.setPriority(Thread.NORM_PRIORITY=3)
線程同步
synchronized 鎖定當前對象
public synchronized void add(String name) { num++; try {Thread.sleep(1);} catch (InterruptedException e) {} // TODO: handle exception System.out.println(name+",you're the NO."+num+"..."); }
在Java語言中,引入了對象互斥鎖的概念,保證共享數據操做的完整性
生產者消費者問題
wait() notify()
wait() sleep():
wait時別的線程能夠訪問鎖定對象,調用wait方法的時候必須鎖定該對象
sleep時別的線程也不能夠訪問鎖定對象