JAVA多線程基礎知識複習一

一.線程的基礎知識:
1.什麼是進程:
它是運行中的程序

2.什麼是線程:
又稱輕量級進程,是程序的最小單元

3.創建線程的兩種方法:
(1)繼承Thread類

public class Demo1{
public static void main(String[] args) {
MyThread mt1=new MyThread();
mt1.start();
MyThread mt2=new MyThread();
mt2.start();
}
}
class MyThread extends Thread{
private int number =5;
@Override
public void run() {
while(true){
System.out.println(“還有”+(number–)+”張票”);
if(number<1){
break;
}
}
}
}

(2)實現Runable接口:

public class Demo2 {
public static void main(String[] args) {
MyThread2 mt2=new MyThread2();
Thread th1=new Thread(mt2);
Thread th2=new Thread(mt2);
th1.start();
th2.start();
}
}
class MyThread2 implements Runnable{
private int number =5;
@Override
public void run() {
while(true){
System.out.println(“還有”+(number–)+”張票”);
if(number<1){
break;
}
}
}
}

4.線程的生命週期:
創建 Thread th =new Thread()
就緒 使用start()方法啓動線程,具有除cpu外所有的資源
運行 佔有cpu 系統真正執行run()方法
阻塞 sleep() synchronized wait()/notify()
死亡 run()方法結束後 interrupt() stop() 終止線程

5.線程同步:
(1)當多個線程訪問同一個數據對象時,會對數據造成破壞
(2)把要競爭訪問的資源用private 修飾(封裝成類或方法)使用synchronized關鍵字或代碼塊
(3)例:銀行取錢:
繼承Thread:
public class Demo4 {
public static void main(String[] args) {
Clent1 clent=new Clent1();
MyThreaed4 mth1=new MyThreaed4(clent);
mth1.start();
MyThreaed4 mth2=new MyThreaed4(clent);
mth2.start();
}
}

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