1. 程式人生 > >S2 第七章_多執行緒

S2 第七章_多執行緒

執行緒改名:

public class Test_03 {
	public static void main(String[] args) {
		Thread thread = new Thread(new MyThread(),"執行緒1");//執行緒改名方法
		System.out.println(thread.getName());
	}

執行執行緒執行緒:

public static void main(String[] args) {
		Thread myThread = new MyThread();
		//myThread.run();
		myThread.start();//執行緒執行用start();
		
		System.out.println(Thread.currentThread().getName());

獲取當前執行緒名字:

public static void main(String[] args) {
		Thread thread = Thread.currentThread();
		System.out.println(Thread.currentThread().getName());//獲取當前執行緒名字

程序的5個狀態:

建立狀態

就緒狀態

執行狀態

阻塞狀態    //不一定有

死亡狀態

優先順序:   執行緒優先順序越高 不一定被先呼叫  只是被呼叫的概率增加

public class Test {
	public static void main(String[] args) {
		MyThread myThread = new MyThread();
		myThread.start();
		
		MyThread myThread2 = new MyThread();
		myThread2.start();
		
		
		System.out.println(myThread.getPriority());//優先順序  預設5   優先級別高的 只是被執行概率高
		System.out.println(myThread2.getPriority());
	}
}

join();

try {
			
			thread2.join();//join方法  讓一個執行緒完了在弄其他執行緒
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

yield();

for (int i = 0; i < 10; i++) {
			try {
				Thread.yield();//執行緒的禮讓    //禮讓不是一定讓出去而是減少被執行的概率  降低自己優先權
			} catch (Exception e) {
				// TODO: handle exception
			}

 synchronized (this) {}//鎖定 同時刻不會搶相同的

Hashtable 安全

StringBuilder 安全效率低