SoFunction
Updated on 2025-04-06

Detailed explanation of Java multithread inheritance Thread class page 2/2

Also share with you the examples of netizens

package JavaThread;class firstThread extends Thread{ private String name = null; public firstThread(String str) {   = str; } public void run() {  for(int i=1;i<=3;i++)  {   ("Thread"++"Third"+i +"implement");   try {    (50);   } catch (InterruptedException e) {        ();   }  } }}class secondThread extends Thread{ private String name = null; public secondThread(String s) {   = s; } public void run() {  for(int i=1;i<=3;i++)  {   ("Thread"++"Third"+i +"implement");   try {    (50);    ();   } catch (InterruptedException e) {     ();   }  } }}public class TestThread{ public static void main(String[] args) {  firstThread p = new firstThread("first");  secondThread pth = new secondThread("second");  (4);  (9);  ();  (); }}

Briefly speaking, inheriting the Thread class

Steps:
a, define the class to inherit the Thread class.
b, overwrite the run method in the Thread class and define the code that needs to be executed by multiple threads into the run method.
c, create a subclass of the Thread class and create a thread object.
d, call the start method, start the thread and call the run method of the thread.

The following is an example to let you intuitively understand how to create threads by inheriting the Thread class.

  /* * Example: Create three threads, print the thread's name every 2 seconds, and print it three times */  public class Thread1 extends Thread{    private final int MAX = 3;//Maximum number of prints    private int COUNT = 1;//count    private final int TIME = 2;//Interval time      //Receive thread name    public Thread1(String name) {      super(name);    }    //coverrunmethod,Write the code we want to execute    public void run() {      while(COUNT<= MAX){        (());        COUNT++;        //After each print,Print after a while        try {          (TIME*1000);        } catch (InterruptedException e) {          ();        }      }    }    public static void main(String[] args) {      Thread1 t1 = new Thread1("Thread 1");//Create thread      Thread1 t2 = new Thread1("Thread 2");      Thread1 t3 = new Thread1("Thread 3");      (); //Start thread      ();      ();      //You can also write in the following way      //new Thread1("Thread 4").start();    }  }

Previous page12Read the full text