Java multithreading, java

Source: Internet
Author: User

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}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.