Java multithreaded Summary thread start

Source: Internet
Author: User
Tags instance method thread thread class

Creation and initiation of threads

The Java language has built-in multithreaded support, and all classes that implement the Runnable interface can be started with a new thread that executes the run () method of the instance, and the thread ends when the run () method finishes executing. Once a thread has finished executing, the instance can no longer be restarted, only a new instance can be rebuilt, and a new thread is started.

The thread class is an instance of the Runnable interface that represents an instance of a thread, and the only way to start a thread is through the thread class's start () instance method:

Thread t = new Thread();
t.start();

The start () method is a native method that starts a new thread and executes the run () method. The thread class default run () method quits without doing anything. Note: Calling the run () method directly does not start a new thread, it is no different from calling a normal Java method.

Therefore, there are two ways to implement your own thread:

Method 1: Your own class extend thread, and the copy run () method, you can start a new thread and execute your own defined run () method. For example:

public class MyThread extends Thread {
public run() {
System.out.println("MyThread.run()");
}
}

Start the thread in the right place: New Mythread (). Start ();

Method 2: If your class is already extends another class, you cannot extends Thread directly, at which point you must implement a runnable interface:

public class MyThread extends OtherClass implements Runnable {
public run() {
System.out.println("MyThread.run() ");
}
}

In order to start mythread, you need to instantiate a thread first and pass in your own Mythread instance:

MyThread myt = new MyThread();
Thread t = new Thread (myt);
t.start();

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.