Java multithreading, java
1. inherit the Thread class to implement Multithreading
Although the method that inherits the Thread class is listed as a multi-threaded implementation method, Thread is essentially an instance that implements the Runnable interface. It represents a Thread instance, and, the only way to start a Thread is through the start () instance method of the Thread class. The start () method is a native method that starts a new thread and runs the run () method. Multithreading is easy to implement in this way. You can use your own class to directly extend the Thread and re-write the run () method to start a new Thread and execute the self-defined run () method. For example:
public class MyThread extends Thread {
Private String name;
Trans (String name ){
This. name = name;
}
@Override
public void run() { for(int i=0;i<10;i++)
{
System.out.println(name+" "+i);
}
} }
Start in the mian Method
MyThread myThread1 = new MyThread ("Zhang San"); MyThread myThread2 = new MyThread ("Li Si ");
Thread dd = new Thread (myThread1 );
Thread ds = new Thread (myThread2); dd. start (); ds. start ();
There is another way to sleep!
This is a class
1 public class Trans extends Thread {2 private String name; 3 4 Trans (String name) {5 this. name = name; 6} 7 @ Override 8 public void run () {9 for (int I = 0; I <100; I ++) {10 11 12 try {13 if (I) % 10 = 0) {14 System. out. println ("-----------------" + I); 15} 16 Thread. sleep (500); 17} catch (InterruptedException e) {18 e. printStackTrace (); 19} 20 System. out. println (name + "" + I + "seconds"); 21} 22 23} 24 25}
Next we will call the main method.
1 public static void main (String [] args) {2 Trans dsTrans = new Trans ("program paused for 0.5 seconds"); 3 Thread ds = new Thread (dsTrans); 4 ds. start (); 5}