歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java多線程相關知識

Java多線程相關知識

日期:2017/3/1 9:12:50   编辑:Linux編程

Java多線程相關知識整理分享。

1)wait() notify() sleep()

sleep是Thread類的函數,wait和notify是Object的函數。

sleep的時候keep對象鎖,wait的時候release 對象鎖。

sleep時監控狀態依然保持。wait進入等待池,只有針對該對象發出了notify才會進入對象鎖池。

Sleep時間過了就會恢復運行,wait後等到notify了,也不一定是立即運行。

Wait和notify是非static函數,sleep是Thread類的static函數。

2)stop() destroy() suspend()

都是Thread類的函數,都不推薦使用。

stop放棄了所有的lock,會使得對象處於一種不連貫狀態。

destroy的時候如果還keep了某些資源的lock,那就死定了

suspend會繼續持有所有的lock,容易發生死鎖。

3)創建線程:

繼承Thread類,override它的abstract函數run

實現Runnable接口,寫run函數。

4)讓線程跑起來:

start()函數

5)例子:四個線程,兩個inc,兩個dec,沒有順序:

public class ThreadTest {

private int j;

public static void main(String[] args) {

ThreadTest tt=new ThreadTest();

Inc inc= tt.new Inc();

Dec dec= tt.new Dec();

for(int i=0;i<2;i++){

Thread t=new Thread(inc);

t.start();

t=new Thread(dec);

t.start();

}

}

private synchronized void inc(){

j++;

System.out.println(Thread.currentThread().getName()

+"-inc:"+j);

}

private synchronized void dec(){

j--;

System.out.println(Thread.currentThread().getName()

+"-dec:"+j);

}

class Inc implements Runnable{

public void run() {

for(int i=0;i<100;i++){

inc();

}

}

}

class Dec implements Runnable{

public void run() {

for(int i=0;i<100;i++){

dec();

}

}

}

}

Copyright © Linux教程網 All Rights Reserved