Java多線程練習


國際慣例,先貼出代碼
package jiankong;

import java.util.Date;

public class jiankong {
	
	public static void main(String [] args) {
		MyThread thread = new MyThread();
		thread.start();
		
		try {
			Thread.sleep(10000);
			System.out.println("捕獲未成功!");
			Thread.interrupted();
		}
		catch (InterruptedException e) {System.out.println("主線程已死!");}//這里不明白catch的含義
	    System.out.println("檢測主線程是否死亡!");
		//thread.interrupt();
	}
}

class MyThread extends Thread {
	boolean flag = true;
	//Thread flag = false;
	public void run() {
		while (flag) {
			System.out.println("+++ " + new Date() + "+++");
			try {
				sleep(1000);
			} catch (InterruptedException e) {
				return;
			}
		}
	}
}

最近寫的,不過多線程好多生疏的地方啊,就上面的這個例子,原來的代碼到是會,然后我修改了下,就再想,既然Thread是主線程,那我能不能中斷主線程呢,我就在catch那里測試,按道理來說,如果主線程被中斷的話,應該會執行的啊,可是調試的時候就是不出。。。。郁悶!!!自學果然吃力不討好

后面附上之前練習的一個小程序:

public class hello {
	public static void main(String args[]) {
		runner r = new runner();
		//r.run();
		Thread t = new Thread(r);
		t.start();

		for (int i = 0; i < 100; i++) {
			System.out.println("main " + i);
		}
	}
}
//class runner {
class runner implements Runnable {
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println("runner " + i);
		}
	}
}



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM