Introduction to Java Threading

Source: Internet
Author: User

Implementation method

There are two implementations of threads in Java:

1. Inheriting the thread class

2. Implement the Runnable interface

Thread class

When the thread class is defined in the Java.lang package, the inherited thread class must override the run () method

Format: Class ClassName extends thread{run () {};}

Start: Thread.Start ();

Runnable interface

Format: Class ClassName implements runnable{run () {};}

Start: ClassName = new runnable (); New Thread (ClassName). Start ();

The difference between inheriting thread and implementing runnable

The pattern of inheriting the thread implementation is to define multiple threads, each of which completes its own task. The pattern for implementing runnable is to define multiple threads to implement a task

In most cases, if you only want to override the run () method without overriding the other Thread methods, you should use the Runnable interface

The state of the thread

Created: A multithreaded object was prepared

Ready: Call the Start () method, waiting for the CPU to dispatch

Run: Execute the Run () method

Blocking: Temporarily stops execution and may give resources to other threads for use

Termination: (death) thread destruction

Common Methods of threading

Get Thread Name: GetName

Get current Thread object: CurrentThread

To determine whether a thread started: isaive

Forced execution of a thread: join, forcing new threads to execute when the main thread executes

Sleep on Thread: sleep

Comity of Threads: Yield

Thread priority (may be performed first than other threads)

1-min_priority

10-max_priority

5-norm_priority do not set the default value is 5

Thread synchronization

You can use synchronized decoration to

Introduction to Java 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.