Packageunit8;ImportJava.applet.Applet;ImportJava.awt.Label;ImportJava.awt.TextField; Public classTestrunnableextendsAppletImplementsrunnable{Label prompt1=NewLabel ("The first thread:"); Label Prompt2=NewLabel ("The second thread:"); TextField Threadfirst=NewTextField (28); TextField Threadsecond=NewTextField (28); Thread thread1,thread2; intCount1=0,count2=0; Public voidinit () {Add (PROMPT1); Add (Threadfirst); Add (PROMPT2); Add (Threadsecond); } Public voidstart () {//creates a thread object with the Run method of the current class and specifies the name of the thread object with a stringThread1 =NewThread ( This, "Firstthread"); Thread2=NewThread ( This, "Secondthread"); Thread1.start (); Thread2.start (); } Public voidrun () {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 ("Number of threads 1 calls:" +count1); }Else if(Currentrunning.equals ("Secondthread") ) {Count2++; Threadsecond.settext ("Number of Threads 2 calls:" +Count2); } } }}
By implementing the Runnable interface to implement the thread, implement the Run method, so that when the main program sleep, the child threads are executed, where the child threads are instance objects of the thread class.
Java Multithreading--Implement Runnable interface