Introduction to Threading

Source: Internet
Author: User

Multi-process: can (concurrently) run multiple tasks (programs) in the operating system

Multithreading: Multiple sequential streams (simultaneous) execution in the same application

Threads (thread) execution process

First generate the thread (NEW), and then enter the ready state (runable), and the time that the CPU executes with the other threads. When the CPU execution time is reached, the running state (Running), the time that the CPU executes during the run may be preempted by other threads, and the thread is ready to wait for the next time it takes to preempt the CPU. A thread may encounter a blocking event while it is running, and then go into a ready state when the blocking state is unblocked. Enter the death state after the thread code has finished running (Dead)

Methods for creating Threads:

Define a thread class, inherit the thread class, and override the Run () method in which the run () method is called the thread body. Because Java only supports single inheritance, classes defined in this way can no longer inherit from other classes.

Class Firstthread extends Thread{public void Run () {for (int i = 0;i < 100;i++) {System.out.println ("firstthread-->" + i);}}}
Class Test{public static void Main (String args[]) {//Generate thread class object Firstthread ft = new Firstthread ();//Start thread, enter ready state, With main thread preemption cpu//ft.run (); can't write like this! Ft.start ();//main thread for (int i =0;i < 100;i++) {System.out.println ("main-->" + i);} Two for loops running in different threads}}

Once you run the test class, there are three threads in the program: main thread, FT thread, garbage collection thread. Main and FT threads run alternately. Multi-threaded operation results are not regular, each result is different

Introduction to Threading

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.