package unit8; import java.applet.Applet; import java.awt.Label; import java.awt.TextField; public class TestRunnable extends Applet implements Runnable{ Label prompt1 = new Label("The first thread:"); Label prompt2 = new Label ("The second thread:"); TextField threadFirst = new TextField(28); TextField threadSecond = new TextField(28); Thread thread1,thread2; int count1=0,count2=0; public void init(){ add(prompt1); add(threadFirst); add(prompt2); add(threadSecond); } public void start(){ //創建線程對象,具有當前類的run方法,並用字符串指定線程對象的名字 thread1 = new Thread(this,"FirstThread"); thread2 = new Thread(this,"SecondThread"); thread1.start(); thread2.start(); } public void run(){ String currentRunning; while(true){ try{ Thread.sleep((int)(Math.random()*3000)); }catch (InterruptedException e) { // TODO: handle exception } currentRunning = Thread.currentThread().getName(); if(currentRunning.equals("FirstThread")){ count1++; threadFirst.setText("線程1調用次數:"+count1); }else if(currentRunning.equals("SecondThread")){ count2++; threadSecond.setText("線程2調用次數:"+count2); } } } }
通過實現Runnable接口來實現所線程,具體實現run方法,這樣當主程序sleep的時候就會執行子線程,這里的子線程都是Thread類的實例對象。
