- By inheriting the thread new thread
The subclass to which the class is declared Thread
. The subclass should override Thread
the method of the class run
. You can then assign and start an instance of the subclass. For example, a thread that calculates a prime number larger than a specified value can be written as:
Class Primethread extends Thread { long minprime; Primethread (Long minprime) { this.minprime = minprime; } public void Run () { //compute primes larger than minprime ... }
The following code then creates and starts a thread:
Primethread p = new Primethread (143);
- Another way to create a thread is to declare a class that implements
Runnable
the interface. The class then implements the run
method. You can then assign an instance of the class that is Thread
passed and started as a parameter at creation time. The same example of using this style is as follows:
Public classtestthread{ Public Static voidMain (String args[]) {Runner run=NewRunner (); Thread T=NewThread (run); T.start (); for(inti=0; i<50; i++) {System.out.println ("Mainthread:" +i); } }}classRunnerImplementsrunnable{ Public voidrun () {System.out.println (Thread.CurrentThread (). isAlive ()); for(inti=0;i<50;i++) {System.out.println ("Subthread:" +i); } }}
Each thread has an identity name, and multiple threads can have the same name. If the thread is created without specifying an identity name, a new name is generated for it.
Because Java only supports single inheritance, it is recommended to use the method of implementing the Runnable () interface new thread
- Working in order to be simple you can use anonymous classes to create threads
Public classtestthread{ Public Static voidMain (String args[]) {//creating threads with anonymous classes NewThread () { Public voidrun () { for(inti = 0;i < 50; i++) {System.out.println ("Subthread:" +i); }}}.start (); for(inti=0; i<50; i++) {System.out.println ("Mainthread:" +i); } }}
The third method is easiest to write and the second one is easiest to maintain.
It is important to note that in web development, things between multiple threads do not affect each other (they are not rolled back or committed together).
How to open a new thread in the Java foundation----application