Approaching concurrent programming one process and thread

Source: Internet
Author: User

Concurrency and parallelism, processes and threads are not only an important concept in the operating system, but also a primer for concurrent programming

The core knowledge that must be understood.

    1. What is concurrency? The difference between concurrency and parallelism

Sequential Programming : All things in a program can only perform one step at any time

concurrency : In the same time period, multiple tasks need to be processed, and only one at a time can be processed, which is concurrency.

Suppose we want to assign multiple tasks to a processor, and if the machine has more than one processor, it's obviously possible to perform these tasks simultaneously, which is parallel .

Unlike parallelism, concurrency is designed to maximize the efficiency of a program on a single processor. The former is physically occurring at the same time, while concurrency occurs logically. , if you want to process task1 within the same time period, task2, you need to switch back and forth between tasks to complete the concurrent execution

Diagram: An example of a simple concurrency

2. multithreading and concurrency in Java

Java is a multithreaded language, and concurrency is one of the most advanced features of Java. For developers of distributed systems and even web systems, it is important to learn efficient concurrent programming. For example, the web system is one of the common applications of Java, and the most basic Java Web Library class servlet is inherently multithreaded, and the graphical user interface is similar to swing and SWT, which is also a thread-safe mechanism. If you don't understand concurrency, it's hard to use these tools well.

3. Processes and Threads

A process can be defined as an instance of an executing program that has its own address space and a Process Control block (PCB) that is used to record the process. Thinking of concurrency, the first thing people think of is through the process. In a multitasking operating system, the CPU periodically switches from one process to another. This implementation is idealized because different processes are in different address spaces and do not interfere with each other, making it easier to implement.

Unfortunately, although the above advantages, because the process will usually have a cost and quantity constraints, want to use the process to concurrent programming is obviously not economical.

Figure: The cost of a process (Task Manager)

Functional Languages can isolate concurrent tasks from one another, a specialized concurrency language that facilitates the processing of a large number of concurrent tasks.

A thread is a task created in a single process that shares the address space and memory resources of a process between threads and threads, and Java concurrency is the introduction of threading mechanisms on a sequential language basis, and concurrency through collaboration between multithreading .

The benefit of multithreading concurrency is the ability to share resources, with less overhead, but also to increase the complexity of the system. However, compared with the convenience of the program design and the load-balancing implementation of resources, the complexity cost becomes insignificant.

4. Creation of Threads

Create a thread in Java, often using the Java.lang.Thread class, creating a thread as follows:

Thread thread  new thread ();

Call the Start () method to start the thread

Thread.Start ();

Since we did not inherit the thread class, the run () method of the thread is overloaded, so there is no action on the thread after start ().

To get the thread to do what we want it to do, we also need to create a subclass of thread to reload the run () method.

5. Create a thread subclass

Give me a chestnut.

 Public class extends Thread {    publicvoid  run () {        System.out.println ("acflood!" );    }}

Run Mythread with the following code

New MyThread (); Mythread.start ();

6. Implement the Runnable interface

We can also implement the run () method by implementing the Runnable interface, and you might ask, what is the difference between runnable and thread? In fact, in the multithreaded mechanism of Java, the implementation of runnable is equivalent to a task, which is what we want the thread to accomplish. The purpose of thread is to drive these tasks, we want to execute the task, just put the runnable instance into thread. For example, the following Countdown task liftoff

 Public classLiftOffImplementsRunnable {protected intCountdown = 10;//Default  Private Static intTaskcount = 0; Private Final intid = taskcount++;  PublicLiftOff () {} PublicLIFTOFF (intCountdown) {       This. Countdown =Countdown; }    PublicString status () {return"#" + ID + "(" + (Countdown > 0?) Countdown: "liftoff!") +")."; }    Public voidrun () { while(countdown--> 0) {System.out.print (status ()); Thread.yield (); //recommendations for thread scheduling    }  }}

We can call the run () method directly to execute the

 Public class Mainthread {    publicstaticvoid  main (string[] args) {        new  LiftOff ();        Laucn.run ();    }}

The better way is to give the thread class to dispatch

 Public class basicthreads{     new Thread (new  LiftOff ());     T.start ();     System.out.println ("Waiting for LiftOff");       }

In this example, the start () method is returned after execution, and then the output main () Waiting for Liftoff,run () in the main thread is finished at the end of the other.

7. Summary

Through the study of this article, I believe that the reader of the basic concept of concurrency, the basic implementation principle of concurrency, as well as the Java multithreading for the creation of a thread has a preliminary understanding. The following sections of this series will continue to explore the details of concurrent programming.

If you think this article is helpful to you, give me some praise

Approaching concurrent programming one process and thread

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.