1. 程式人生 > >演算法小題(三):兩執行緒交替輸出1~99

演算法小題(三):兩執行緒交替輸出1~99

一、回顧Thread的常用法方法

  • 1.start():啟動執行緒並執行相應的run()方法
  • 2.run():子執行緒要執行的程式碼放入run()方法中
  • 3.currentThread():靜態的,調取當前執行緒
  • 4.getName():獲取此執行緒的名字
  • 5.setName():設定此執行緒的名字
  • 6.yield():呼叫此方法的執行緒釋放當前CPU的執行權
  • 7.join():在A執行緒中呼叫B執行緒的join()方法,表示:當執行到此方法,A執行緒停止執行,直至B執行緒執行完畢,A執行緒再接著join()之後的程式碼執行
  • 8.isAlive():判斷當前執行緒是否還存活
  • 9.sleep(long l):顯式的讓當前執行緒睡眠l毫秒
  • 10.執行緒通訊:wait() notify() notifyAll()
  • 設定執行緒的優先順序
    • getPriority() :返回執行緒優先值
    • setPriority(int newPriority) :改變執行緒的優先順序

二、倆執行緒交替輸出1~99 

public class ThreadTest implements Runnable{

	int i = 1;
	@SuppressWarnings("static-access")
	@Override
	public void run() {
		while(true){
			/*
			 *  指代執行緒T,使用implement方式
			 *  若繼承Thread,慎用this
			 */
			synchronized (this) {
				notify();
				try {
					Thread.currentThread().sleep(300);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if(i<100){
					System.out.println(Thread.currentThread().getName()+":"+i );
					i++;
					// 放棄資源,等待
					try {
						wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	
	public static void main(String[] args){
		ThreadTest T = new ThreadTest();
		Thread t1 = new Thread(T,"執行緒1");
		Thread t2 = new Thread(T,"執行緒2");
		t1.start();
		t2.start();
		
	}
}