線程是程序中的執行線程。
線程有兩種實現方法。
一種是創建一個類來繼承Thread父類,並覆寫run方法。
格式:
public class Extends_Thread extends Thread{
public void run(){
//代碼塊
}
}
第二種是創建一個類來實現Runnable接口,其接口中只有run方法。
public class Implements_Runnable implements Runnable{
public void run(){
//代碼塊
}
}
那麼其是如何實例化的呢?實例化如下:
public class Test{
public static void main(String []args){
new Extends_Thread().start();
new Thread(new Implements_Runnable()).start();
}
}
多線程會出現異步的問題。如賣票的情況,會出現賣出-1票。要解決這個異步問題,就要使用同步代碼塊或者同步函數。
同步代碼塊的格式如下:
synchronized (同步鎖){
//代碼塊
}
同步函數的格式如下:
synchronized 方法(參數){
//代碼塊
}
線程的賣票代碼、多生產與多消費問題的代碼已經實現了,在我的空間中的代碼區中:http://my.csdn.net/wo3002807/code
多線程的個人總結
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.