Java thread implementation

Source: Internet
Author: User

Java thread implementation
1. Process and thread processes are a dynamic execution process of the program, which goes through a complete process from code loading, execution to execution completion. The multi-process operating system can run multiple processes (programs) at the same time. Because the CPU has a time-sharing mechanism, each process can obtain its own CPU time slice cyclically. Because the CPU runs fast, it seems that all programs are running at the same time. Threads are further divided based on processes. Multithreading means that a process can generate multiple threads during execution. These threads can exist and run simultaneously. The multi-threaded mechanism can run multiple program blocks at the same time. When a thread contains time-consuming operations (such as loops), another thread can perform other processing. Traditional programming languages can run only one block at a time. In case of time-consuming operations, they can only execute consumption operations in order to continue executing the program. 2. java Thread implementation ① inherit Thread class syntax class name extends Thread {// inherit Thread class attributes ...; // define the property method in the class ...; // define the method in the class public void run () {// overwrite the run () method in the Thread class. This method is the main body of the Thread // Thread body} example: ThreadDemo. java class MyThread extends Thread {private String name; public MyThread (String name) {this. name = name;} public void run () {for (int I = 0; I <10; I ++) {System. out. println (name + "run, I =" + I) ;}} public class ThreadDemo {Public static void main (String [] args) {// TODO Auto-generated method stub MyThread mt1 = new MyThread ("thread "); myThread mt2 = new MyThread ("thread A"); mt1.start (); mt2.start () ;}note: Use the start () method to start multithreading instead of running () method to start the thread. The start () method calls the start0 () method, and the start0 () method uses the native keyword to declare that the implementation of multithreading must be supported by the underlying operating system. The Thread class is inherited to implement multithreading. The same Thread class object can only call the start () method once. If it is called multiple times, an IllegaIlThreadStateException exception is thrown. Source code:

 public synchronized void start() {        /**         * This method is not invoked for the main method thread or "system"         * group threads created/set up by the VM. Any new functionality added         * to this method in the future may have to also be added to the VM.         *         * A zero status value corresponds to state "NEW".         */        if (threadStatus != 0)            throw new IllegalThreadStateException();        /* Notify the group that this thread is about to be started         * so that it can be added to the group's list of threads         * and the group's unstarted count can be decremented. */        group.add(this);        boolean started = false;        try {            start0();            started = true;        } finally {            try {                if (!started) {                    group.threadStartFailed(this);                }            } catch (Throwable ignore) {                /* do nothing. If start0 threw a Throwable then                  it will be passed up the call stack */            }        }    }

 

Private native void start0 (); ② implement the Runnable interface Syntax: class name implements Runnable {// implement the Runnable interface attributes ...; // define the property method in the class ...; // class definition method public void run () {// overwrite the run () method in the Runnable interface // thread body} example:
RunnableDemo. java class MyThread01 extends Thread {private String name; public MyThread01 (String name) {this. name = name;} public void run () {for (int I = 0; I <10; I ++) {System. out. println (name + "run, I =" + I) ;}} public class RunnableDemo {public static void main (String [] args) {// TODO Auto-generated method stub MyThread mt1 = new MyThread ("thread A"); MyThread mt2 = new MyThread ("thread "); thread t1 = new Thread (mt1); Thread t2 = new Thread (mt2); t1.start (); t2.start ();}}

 

The start () method in the Thread class is required to start the Thread. The run () method in the Thread class calls the run () method in the Runnable interface. This method is completed by the Runnable subclass, therefore, if multiple threads are implemented by inheriting the Thread class, the run () method must be overwritten. The constructor In the Thread class accepts the Child class of Runnable, so this Thread can be started through the Thread class. Source code:
private Runnable target;public Thread(Runnable target,String name){    init(null,target,name,0);}...public void run(){    if(target != null){        target.run();    }}

 

Using the Runnable interface to implement multithreading can avoid restrictions caused by java's single inheritance. Note: 1. why java does not support multi-inheritance and multi-inheritance is mainly because many methods with the same name or attributes with the same name are easy to remember. However, interfaces are method rewriting and an interface usually has a specific method, although the methods are the same, they can be distinguished by different interfaces.

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.