Create a thread by creating an object that implements the runnable interface and using it as the target object of the thread. Runnable interface: defines an abstract method run (). Definition: Public interface java. Lang. runnable { Public abstract void run (); } The overall framework is as follows: Class myrunner implements runnable { Public void run (){ ... } } Myrunner r = new myrunner (); Thread t = new thread (threadgroup group, runnable target, string name ); See example: Threadtesterer. Java Threadtest. Java For example: Public class clock extends java. Applet. Applet Implements runnable { Thread clockthread; Public void start (){ If (clockthread = NULL ){ Clockthread = new thread (this, "Clock "); Clockthread. Start (); } } Public void run (){ While (clockthread! = NULL ){ Repaint (); Try { Clockthread. Sleep (1000 ); } Catch (interruptedexception e ){ } } } Public void paint (Graphics g ){ Date Now = new date (); G. drawstring (now. gethours () + ":" + Now. getminutes () + ":" + Now. getseconds (), 5, 10 ); } Public void stop (){ Clockthread. Stop (); Clockthread = NULL; } } This is a clock applet that displays the current time and updates every second. The applet uses the runnable interface to provide the run () method for its thread. The class clock is extended by the class applet, but it also requires a thread to update and display the time. Java does not support multiple inheritance, so it cannot inherit the Thread class, but uses the runnable interface. First, a thread named clockthread is constructed in the START () method and the thread. Start () method is called to start the thread. That is, the system thread relationship is established during Java runtime. The following statement creates a new thread: Clockthread = new thread (this, "Clock "); This is the first independent variable in the thread constructor. As the target object of the thread, it must implement the runnable interface. In this constructor, the thread clockthread uses the run () method in its runable target object as its run () method. In this example, the target object is the clock applet. The second variable in the constructor is the thread name. After the thread is started, call the run () method of the target object unless the thread is stopped. In the loop of the run () method, the applet redraws itself and then sleeps for 1 second. At the same time, it needs to capture and process exceptional events. If you leave the page showing the clock, the application will call the stop () method to leave the thread empty. When you return, a new thread is created. In a specific application, the method used to construct the thread body depends on the situation. Generally, when a thread has inherited another class, it should be constructed using the second method to implement the runnable interface. |