Java concurrent Programming--basic threading mechanism 1

Source: Internet
Author: User

First, why need concurrent programming

In the case of single-threaded programming, if a program encounters a blocking situation, such as an event that waits for I/O to occur, the program can be executed. This will affect the operation of the following programs.

Concurrency is the process in which multiple tasks are processed and each task is switched back and forth from the operating system.

It feels like many tasks are executed at the same time.

Second, the basic threading mechanism

1. Define Tasks

Define a class, implement the Runnable () interface, define the run () method in the runnable () interface, and we can write the event to be executed in the run () method.

The run of the task in run () needs to be placed in the thread constructor.

After you run the thread through the Start method, the tasks in thread are run.

Class Task1 implements runnable{public    void Run ()   {for   (int. x=0;x<=10;x++)   {for   (int y=0;y <=99999999;y++) {}system.out.println (Thread.CurrentThread (). GetName () + ".... x=" +x);}}   Class Task2 implements runnable{public    void Run ()   {for   (int. z=0;z<=10;z++)   {for   (int y=0;y <=99999999;y++) {}system.out.println (Thread.CurrentThread (). GetName () + ".... z=" +z);}}   public class Hello {public static void main (string[] args) {Task1 t1= new Task1 (); Task2 t2 = new Task2 (); Thread nt1 = new Thread (t1); Thread nt2 = new Thread (t2); Nt1.start (); Nt2.start ();}}


Java concurrent Programming--basic threading mechanism 1

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.