Creation of threads for Java concurrency (i)

Source: Internet
Author: User

    1. Introduction

      Recently in learning concurrency, so I searched on the internet a "Java Concurrency Programming Practical" book learning.

    2. How traditional threads are created (before JDK 1.5)

      There are two ways to create threads in my impressions

      1. Inherit the thread class, rewrite the Run method, instantiate itself to write the thread subclass, and open with the start () method.

      2. Implement the Runnable interface, override the Run method, pass the instance object of the Runnable subclass as the thread's construction parameter, create the threads, and turn on.

      But most of the time I look at other people's code in the first way, just new Thread and then rewrite the Run method. In fact, the second way is more consistent with object-oriented programming, because thread is a thread, he just create and open threads, and should not be logical processing code to write inside, logical processing should be given to the runnable subclass.

    3. Traditional ways to create timers

      The traditional timer is the timer class, the way to create

timer timer = new timer (); Timer.schedule (New timertask () { //Create timer task      @Override      Public void run ()  {        system.out.println ("Hello");     }},2000)   //2 seconds after printing Hello Timer.schedule (new timertask () {      @Override     public void run ()  {         system.out.println ("Hello");     }},2000,3000)  //2 seconds to print Hello, then print once every 3 seconds hello. 

There is a requirement here to print after 2 Hello , print after 3 seconds The World ... , and then continue to cycle through the printing. What should I do?

Ideas: 1. I can create two timer tasks, Task1 Task 2 seconds after printing Hello, task2 task 3 seconds after printing, and then at the end of the Task1 task to open Task2, at the end of Task2 to open Task1

2. You can create only one task, so that after doing a flag tag outside, when True is to perform a print Hello, then open a new task at the end, and put Flag=!flag;

The first implementation of public static void main (string[] args) {new Timer (). Schedule (New MyTimerTask1 (), N), while (true) {System.out . println (New Date (). getseconds ()), try {thread.sleep (),} catch (Interruptedexception e) {//TODO auto-generated Catch Blocke.printstacktrace ();}}} Static Class MyTimerTask1 extends TimerTask {@Overridepublic void run () {System.out.println ("Hello"); new Timer (). Schedule (New MyTimerTask2 (), 3000);}} Static Class MyTimerTask2 extends TimerTask {@Overridepublic void run () {System.out.println ("Wrold"); new Timer (). Schedule (New MyTimerTask1 (), 2000);}}}

The second kind can not be posted.

Creation of the thread pool

Creating a thread pool using the Executors tool class

Introduction to the API:

Newfixedthreadpool creates a fixed-length thread pool, and when the maximum number of threads is reached, the size of the thread pool will no longer change.

Newcachedthreadpool creates a cacheable thread pool that reclaims empty threads if the current thread pool size exceeds the processing requirements, and increases the number of threads when the demand increases; the thread pool is unlimited in size.

Newsinglethreadpoolexecutor Create a single-threaded executor to ensure that the task is right, serial execution (this single thread dies and there is a thread animations for him)

public static void Main (string[] args) {Executorservice ThreadPool = Executors.newfixedthreadpool (3);//1th type// Executorservice ThreadPool = Executors.newcachedthreadpool ();//2nd Type//Executorservice ThreadPool = Executors.newsinglethreadexecutor ();//3rd type for (int i = 1; i <=; i++) {final int task = I;threadpool.execute (New Runna  ble () {@Overridepublic void Run () {for (int j = 1; J <= 5; j + +) {try {Thread.Sleep]} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "is looping of" + j + "for task of" + Task);}});}}

10 missions to 3 kinds of thread pool to complete,

Results

The result of the 1th kind  10 a task with only one fixed 3 threads to complete the task Pool-1-thread-1 is looping of 1 for  task  of 1pool-1-thread-3 is looping of 1 for  task of  3pool-1-thread-2 is looping of 1 for  task of 2pool-1-thread-1  is looping of 2 for  task of 1pool-1-thread-2 is  Looping of 2 for  task of 2pool-1-thread-3 is looping of  2 for  task of 3pool-1-thread-2 is looping of 1 for   task of 6pool-1-thread-1 is looping of 1 for  task  of 4pool-1-thread-3 is looping of 1 for  task of  5pool-1-thread-3 is looping of 2 for  task of 5pool-1-thread-3  is looping of 3 for  task of 3pool-1-thread-2 is looping of 4 for   Task of 2 the 2nd kind of result  10 a task to open 10 threads to complete pool-1-thread-1 is looping of 1 for   task of 1pool-1-thread-3 is looping of 1 for  task  of 3pool-1-thread-2 is looping of 1 for  task of  2pool-1-thread-9 is looping of 1 for  task of 9pool-1-thread-10  is looping of 1 for  task of 10pool-1-thread-6 is  Looping of 1 for  task of 6pool-1-thread-5 is looping of  1 for  task of 5pool-1-thread-4 is looping of 1 for   task of 4pool-1-thread-8 is looping of 1 for  task  of 8pool-1-thread-7 is&nBsp;looping of 1 for  task of 7pool-1-thread-3 is looping of  2 for  task of 3pool-1-thread-1 is looping of 2 for   task of 1pool-1-thread-2 is looping of 2 for  task  of 2pool-1-thread-7 is looping of 2 for  task of  7pool-1-thread-4 is looping of 2 for  task of 4pool-1-thread-5  is looping of 2 for  task of 5pool-1-thread-9 is  Looping of 2 for  task of 9pool-1-thread-8 is looping of  2 for  task of 8pool-1-thread-6 is looping of 2 for   task of 6pool-1-thread-10 is looping of 2 for  task  of 10 the 3rd kind of results,  10 a mission that only started.A thread pool-1-thread-1 is looping of 1 for  task of 1pool-1-thread-1  is looping of 2 for  task of 1pool-1-thread-1 is  Looping of 1 for  task of 2pool-1-thread-1 is looping of  2 for  task of 2pool-1-thread-1 is looping of 1 for   task of 3pool-1-thread-1 is looping of 2 for  task  of 3pool-1-thread-1 is looping of 1 for  task of  4pool-1-thread-1 is looping of 2 for  task of 4pool-1-thread-1  is looping of 1 for  task of 5pool-1-thread-1 is  Looping of 2 for  task of 5pool-1-thread-1 is looping of  1 for  task of 6pool-1-thread-1 is looping of 2 for  task of  6pool-1-thread-1 is looping of 1 for  task of 7pool-1-thread-1  is looping of 2 for  task of 7pool-1-thread-1 is  Looping of 1 for  task of 8pool-1-thread-1 is looping of  2 for  task of 8pool-1-thread-1 is looping of 1 for   task of 9pool-1-thread-1 is looping of 2 for  task  of 9pool-1-thread-1 is looping of 1 for  task of  10pool-1-thread-1 is looping of 2 for  task of 10


Newscheduledthreadpool is the same as timer and timer, but only one thread inside the timer is performing the task, while Newscheduledthreadpool is able to set multiple threads

Executors.newscheduledthreadpool (3). Scheduleatfixedrate (New Runnable () {@Overridepublic void run () { System.out.println ("bombing!");}}, 6, 2, timeunit.seconds);


Creation of threads for Java concurrency (i)

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.