Getting Started in Java Thread - Defining RUN Method in Threads

xiaoxiao2021-03-06  76

The RUN method is the code that needs to be executed when running the thread. (You want to use code - that is

Run () method - describes a process instead of creating an object representing this process. There is always a controversy in how to understand the thread. This depends on, you are thinking of threads as an object or processing. If you think it is a process, then you get rid of "all things"

OO dogma. But at the same time, if you just want this processing process to take a part of the program, then you have no reason to make the entire class become

Runnable. In view of this, the thread code is hidden in the form of an internal class, which is usually a more sensible choice. From Tij3. )

in

In the Java language, we can achieve our two ways.

RUN method:

1, cover

Java.lang.thread

Public void run () method.

Public class simplethread extends thread {

Public SimpleThread (String Str) {

Super (STR);

}

Public void run () {

For (int i = 0; i <10; i ) {

System.out.println (i " GetName ());

Try {

Sleep ((long) (Math.random () * 1000);

} catch (interruptedexception e) {

}

}

System.out.println ("DONE!" GetName ());

}

} Call the thread defined above: public class twothreadsdemo {

Public static void main (String [] args) {

New SimpleThread ("jamaica"). start ();

New SimpleThread ("Fiji"). start ();

}

} 2, implement java.lang.Runnable interface: import java.awt.graphics;

Import java.util. *;

Import java.text.dateFormat;

IMPORT JAVA.Applet.Applet;

Public Class Clock Extends Applet Implements Runnable {

Private thread clockthread = NULL;

Public void start () {

IF (clockthread == null) {

ClockThread = New Thread (this, "clock");

Clockthread.start ();

}

}

Public void run () {

Thread mythread = thread.currentthread ();

While (clockthread == mythread) {

Repaint ();

Try {

Thread.sleep (1000);

} catch (interruptedexception e) {}

}

}

Public void paint (graphics g) {

Calendar Cal = Calendar.getInstance ();

Date Date = Cal.getTime ();

DateFormat Dateformatter = DateFormat.getTimeInstance ();

g.drawstring (Dateformatter.Format (Date), 5, 10);

Public void stop () {

Clockthread = NULL;

}

}

转载请注明原文地址:https://www.9cbs.com/read-105027.html

New Post(0)