標籤:style 暫停 blog imp 方法 優先 system static 線程
線程的概念在此不再贅述。
下面介紹三種啟動線程的方式。
1. 繼承Thread
public class ThreadTest extends Thread { @Override public void run() { int i = 0; while (i < 10){ i++; System.out.println("this is Thread thread"); } }}
調用
ThreadTest threadTest = new ThreadTest();threadTest.start();
2. 實現Runnable介面
public class RunnableTest implements Runnable{ int a; int b; public RunnableTest(int a, int b){ this.a = a; this.b = b; } public void run(){ int i = 0; while (i < 10){ i++; System.out.println("a:" + a + " b:" +b); } }}
調用
RunnableTest threadExtends2 = new RunnableTest(5,6);new Thread(threadExtends).start();
3. 匿名類
Thread t = new Thread(){ public void run(){ int i = 0; while (i < 10){ i++; System.out.println("this is Inside Thread"); } }};t.start()
線程常用方法:
1. sleep 線程暫停,睡會再執行。
2. join 加入到當前線程中,若加入,則先執行加入的線程,後執行當前線程。
3. setPriority 設定線程優先順序。
4. yield 臨時暫停。
下面介紹一種定時執行任務的方法,用的是TimerTask
public static void main(String args[]){ Timer t = new Timer(); TimerTask timerTask = new TimerTask() { int i = 0; @Override public void run() { System.out.println(i); i++; if (i == 5) t.cancel(); } }; t.scheduleAtFixedRate(timerTask,0,1500);
java線程以及定時任務