Multithreading in Java

Source: Internet
Author: User

Keywords: Thread, Runnable, synchronized

The current CPU is very powerful, generally multiple cores, and uses hyper-threading technology, so that one core can run multiple threads in parallel. When processing big data, multithreading will greatly speed up data processing, and multi-threaded programming is also becoming increasingly important. In Java, each program is running with a main thread.

Two ways to create a Thread: Inherit the Thread and implement Runnable

Class A extends Thread

Thread implements Runnable

Directly calling the run () method is not a multi-thread, but a method for running objects. To create multiple threads, you need to call the operating system resource-CPU. In the Thread's start () method, native's start () is called to create a new Thread (native Description: http://blog.csdn.net/fsz521/article/details/8748562 ).

For example, multiple threads control sequential execution: three threads output their IDs in sequence.

Output: 012012012

package multiThread;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;class TestThreadMethod extends Thread {public TestThreadMethod(String name) {super(name);}public void run() {System.out.print(this.getName());}}public class TestThread {public static void main(String[] args) {TestThreadMethod ttm0 = new TestThreadMethod("0");TestThreadMethod ttm1 = new TestThreadMethod("1");TestThreadMethod ttm2 = new TestThreadMethod("2");ExecutorService exec = Executors.newSingleThreadExecutor();for (int i = 0; i < 3; i++) {exec.execute(ttm0); exec.execute(ttm1);exec.execute(ttm2);}exec.shutdown();}}

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.