線程學習總結

1.線程的概念:一個進程中同時執行的多個單元。(比如一段代碼中有兩個while打印語句,若不使用線程的話期執行爲先後順序,反之使用線程能併發執行)

2. 線程的創建:

     (1)繼承Tread類:

public class Example {
  public static void main(String[] args) {
	MyThread mt = new MyThread();
	mt.start();
	while(true){
		System.out.println("執行了主函數裏的while語句");
	}
}
}
class MyThread extends Thread{
	public void run() {
		while(true){
			System.out.println("執行了線程裏的while語句");
		}
	}
}
       (2)實現Runnalbe接口:

         

public class Example {
  public static void main(String[] args) {
	MyThread mt = new MyThread();
	Thread thread = new Thread(mt);
	thread.start();
	while(true){
		System.out.println("執行了主函數裏的while語句");
	
	}
}
}
class MyThread implements Runnable{
	public void run() {
		while(true){
			System.out.println("執行了線程裏的while語句");
		}
	}
}

3.線程的休眠:

      線程暫停,將CPU讓給別的線程。

	public void run() {
		while(true){
			System.out.println("執行了線程裏的while語句");
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
4.線程的Join()方法:

    線程對象名.join() 在其他進程中時,將使其他進程阻塞,直到調用join方法的線程執行完,即所謂的線程插隊。


5.線程同步問題:

   將線程共享的資源的操作方法或代碼塊放在synchronized定義的區域時,在某一時間之內允許一個線程訪問,其他線程發生阻塞直到當前線程執行完畢。

    同步方法格式:synchronized 返回值類型 方法名 ([參數1,^]){}

   注意:使用同步方法時要保證同步的方法被所有線程共享,方法所在的對象對於所有對象是唯一的,從而保證了鎖的唯一。

6.線程等待問題:

public class Custmer extends Thread {
	// 定義一個集合
	private ArrayList<IPhone> list;

	// 構造方法傳遞參數方式,初始化list
	public Custmer(ArrayList<IPhone> list) {
		this.list = list;
	}

	public void run() {
		synchronized (list) {
			while (true) {
				if(list.size()==0){
					try {
						list.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				//取出一個產品
				IPhone iphone = list.remove(0);
				System.out.println("消費者購買了一個手機,型號是:"+iphone.getName());
				list.notify();
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}


在該過程中需要用到同步鎖synchronized,其中 wait()方法是當前線程進入等待,直到其他線程調用notify()方法喚醒爲止。






發佈了27 篇原創文章 · 獲贊 12 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章