To enable the object to be multithreaded, simply inherit the Java.lang.Thread class or implement the Java.lang.Runnable interface. Java threads are implemented through the Java.lang.Thread class. After generating a thread class object, a new thread is created. This instance object enables you to start, terminate, suspend threads, and so on. It is constructed in the following way:
Public Thread (Threadgroup group,runnable target,string name);
The first parameter is the thread group to which the thread belongs, and target is the object that actually executes the thread body, which must implement the interface Runnable;name is the thread name
In addition, when a parameter is NULL, there are several methods
public Thread ();
Public Thread (Runnable target);
Public Thread (Runnable target,string name);
Public Thread (String name);
Public Thread (Threadgroup group,runnable target);
Public Thread (threadgroup group,string name);
Any object that implements an interface runnable can be a target object for a thread. The thread class itself also implements the interface runnable, so the line Cheng can be implemented in two ways:
(1), define a thread class, inherit the thread class, and override the Run () method in it. At this point, when initializing an instance of this class, target can be null, indicating that the instance object is executed.
classcomputersum{intsum; Public voidSetsum (intN) {Sum=N; } Public intgetsum () {returnsum; }}classPeopleextendsthread{inttimelength; Computersum CS; People (String s,inttimelength,computersum sum) {SetName (s);//Call the SetName () of the thread class This. timelength=timelength; CS=sum; } Public voidrun () { for(inti=1;i<=5;i++){ intm=cs.getsum (); Cs.setsum (M+1); System.out.println ("I Am" +getname () + ", and:" +cs.getsum ()); } Try{sleep (timelength); }Catch(Interruptedexception e) {} }} Public classchildthread{ Public Static voidMain (String args[]) {people teacher,student; Computersum sum=Newcomputersum (); Teacher=NewPeople ("Teacher", 200, sum); Student=NewPeople ("Student", 200, sum); Teacher.start (); Student.start (); }}
(2), to provide a class to implement the interface runnable as a target object of a thread, in the initialization of a thread class or threads subclass of the threading object, the target is passed to the thread instance, the target object provides thread body run ().
classAImplementsrunnable{Thread th; A () {th=NewThread ( This, "Demo Thread"); } Public voidrun () {System.out.println ("Class A implements the Runnable interface and can inherit other classes"); }} Public classrunnablethread{ Public Static voidMain (String args[]) {A A=NewA (); A.th.start (); System.out.println ("This is the main thread"); }}
Java Create thread