I. About Threads
- Threads are the basic unit of executing Java program code
- Java threads are part of the Java platform
Two. Threading Programming in Java
Thread class
The thread in Java has been encapsulated as the thread class, and the Void Start () method is the method that initiates the thread, and the call causes the thread to execute the specified method. void run () is one of the methods, and the start () method takes it as a starting point for the thread.
Just let a class inherit the thread class and then overwrite the run () method, then you can control the thread.
1 Public classusethread{2 Public Static voidMain (string[] args) {3MyThread thread =NewMyThread ();4 Thread.run;5 }6 }7 classMyThreadextendsthread{8 Public voidrun () {9System.out.println ("This is a thread code"));Ten } One}
However, a class can only implement single inheritance, and if you inherit the thread class, you cannot inherit other classes, so it is better to use an interface. Java provides the runnable () interface, which includes the run () method. The thread class contains the Runnable attribute, which can be constructed as thread (Runnable), and the Run () method can be enabled as long as Runnable is not null.
public class Usethread {
Public Static void Main (string[] args) { new myrunnable (); New Thread (runnable); Thread.run (); }} class Implements runnable{ publicvoid run () { System.out.println ("This is a thread code" ); }}
PackageStudy_java; Public classInner { Public Static voidMain (string[] args) {Printcurrentthread printer=NewPrintcurrentthread (); //Anonymous Inner classRunnable Runnable =NewRunnable () { Public voidrun () {Printcurrentthread P=NewPrintcurrentthread (); P.printcurrrentthread (); } }; Thread Thread=NewThread (runnable, "thread-1"); Thread.Start (); Printer.printcurrrentthread (); }}classprintcurrentthread{ Public voidPrintcurrrentthread () {Thread CurrentThread=Thread.CurrentThread (); String ThreadName=Currentthread.getname (); System.out.println (ThreadName); }}
Java multithreaded programming