Java Multithreading--< > overview, defining Tasks

Source: Internet
Author: User

I. Overview

Why Use Threads? Starting with C, the default order of execution for any high-level language is "executed in the Order of code written", and the business logic written during the daily development process, whatever does not involve concurrency, is to have a task order executed to ensure that the desired result is obtained. However, when your task needs to deal with a long time, and there is no dependency between the business (for example, a execution of the process B can also be executed, b there is no need to wait for a to execute before executing), then we can split a task into several small tasks.

For example, task A is responsible for receiving keyboard input, B is responsible for some parameters and calculations ahead of time (assuming a large amount of computation), C is responsible for the input of A and B and the results. At this point, if the ABC sequence executes, if the input of a is blocked and waiting for user input, B cannot execute, while the CPU is in a vacant state (assuming a single CPU and single core), the efficiency is not high.

Another idea, if: ABC separate into three tasks, a input is blocked, then the B to the CPU to execute, after the user input results, B has calculated the results of the output to C, at this time, the user submitted, C immediately calculated the results.

Comprehensive: Multithreading solves the problem of concurrency, the purpose is to make task execution more efficient, the implementation of the premise is "blocking." They appear to be executing at the same time, but are actually just a time slice to try out the CPU.

Second, multithreading in Java

1. Defining tasks

Task: In short, it is a collection of sequences of work, which have a sequence of tasks that, after execution, will achieve a result or achieve a purpose.

First, consider a question, why do you define a task? As a Java programmer, we do not care how the underlying multithreading mechanism is executed, only concerned about how I write a task, Java's underlying multithreading mechanism to understand, in order to invoke your task to execute. Java is the definition of the Runnable interface for you to implement, meaning: you implement the Runnable interface class to define a class, the object of the class is I can identify the task, other methods defined by the program, I will not think of it as a task.

Well, to be clear here, we're only talking about tasks at this point, not multithreading. There is no difference between a task and the code you write in a class, except that you implement an interface as required by Java and write your code in the Run method of that interface. That is, you usually want to write a class, the class can do some functions, any method in this class, variables are defined by yourself, and when writing a task, you need to implement the Runnable interface, the code you want the implementation of the task to write to the Run method, of course, You can then define other variables, methods in the task class that you define to be called in run.

2. Code implementation

 Public classTaskImplementsRunnable {    protected intCountdown = 10; Private Static intTaskcount = 0 ; Private Final intid = taskcount++;  PublicTask () {} PublicTask (intCountdown) {         This. Countdown =Countdown; }     PublicString status () {return"#" +id+ "(" + (Countdown>0?countdown: "task!")    +"). "; } @Override Public voidrun () { while(countdown-->0) {System.out.print (status ());        Thread.yield (); }    }}

Note: The code here stems from "thinking in Java"

Defines a task that does not involve multi-threading at this time, so the task itself is a class, and its objects can be called anywhere we try, for example:

 Public class Taskmain {     Public Static void Main (string[] args) {        new  Task ();        Task.run ();    }}

is to declare the object of the instance in main, and call its run method, just as we would normally create a class to invoke the object's method.

At this point, a task is defined. That is to say, according to Java requirements, we have implemented a simple task. However, the purpose of implementing the task is not just to implement the task, but to allow the multithreaded mechanism to invoke the task to execute. See: Java multithreading--< two > handing tasks to threads, thread declaration

Java Multithreading--< > overview, defining Tasks

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.