Java Multi-Threading

Source: Internet
Author: User
Tags ticket

Concept:

1. Threads: Control flow in a separate sequence in a program

The thread itself relies on the program to run

Threads are sequential control flows in a program and can only use resources and environments that are assigned to programs


2. Process: procedures in progress

A process can contain one or more threads

A process must contain at least one thread


3. Single-threaded: There is only one thread in the program, in fact the main method is a main path


4. Multithreading: Multithreading is a program that runs multiple tasks

The purpose of multithreading is to better use CPU resources


The state of the thread:

Create state: A multithreaded object is prepared;

Ready state: Called the Start () method, waiting for the CPU to dispatch;

Run state: Executes the run () method;

Blocking state: Temporarily stops execution and may give resources to other threads for use;

Termination state (Dead State): Thread destruction;


Thread Common methods:

1. Get thread name getName ()

2. Get the current thread object CurrentThread ()

3. Determine if the thread is starting isAlive ()

4. Thread's forced run join ()

5. Hibernate sleep for Thread ()

6. The thread's comity yield ()


Synchronization and deadlock of threads:

1. Synchronizing code blocks

When you add the "synchronized" keyword to a code block, this code block is called a synchronous code block

2. Synchronizing code block formats

Synchronized (synchronization object) {

Code blocks that need to be synchronized;

}

3. Synchronization method

In addition to the code block can be synchronized, the method can also be synchronized

4. Method synchronization Format

synchronized void Method name () {}


Classic example of synchronization of threads:

Simulate a station there are three windows at the same time sell tickets, the total number of votes is 10, sold out so far, the code is as follows:

Sell ticket Thread class MyThread implements Runnable {//Original ticket number is 10 tickets private int ticket = ten; @Overridepublic void Run () {//Dead loop Sell ticket while (t Rue) {if (Ticket > 0) {try {thread.sleep (500); System.out.println (Thread.CurrentThread (). GetName () + "sell a ticket ..."); catch (Exception e) {e.printstacktrace ();} System.out.println ("Number of votes left:" +--ticket);} else {//The ticket has been sold out, the window stops the ticket break;}}}} public class Test001 {public static void main (string[] args) {//There are now three windows at the same time selling tickets MyThread r = new MyThread (); thread T1 = new Thread (r, "window One"); Thread t2 = new Thread (r, "window Two"); thread t3 = new Thread (r, "window three");//start concurrent selling ticket T1.start (); T2.start (); T3.start ();}}


The results of the program run as follows:

Window one sold a ticket ... Number of votes left: 9 window three sell a ticket ... Votes left: 8 window two sell a ticket ... Number of votes left: 7 window one sold a ticket ... Number of votes left: 6 window three sell a ticket ... Votes left: 5 window two sell a ticket ... Number of votes left: 4 window three sell a ticket ... Number of votes left: 3 window one sold a ticket ... Votes left: 2 window two sell a ticket ... Number of votes left: 1 window one sold a ticket ... Number of votes left: 0 window three sell a ticket ... Remaining votes:-1 window two sell a ticket ... Number of votes left:-2


Because three windows is a concurrent sell ticket, so pawn ticket only one time, three windows at the same time to sell it, will cause the remaining votes to become negative, this time need to synchronize access to this ticket resources to solve this problem, the code is amended as follows:

Sell ticket Thread class MyThread implements Runnable {//Original ticket number is 10 tickets private int ticket = ten; @Overridepublic void Run () {//Dead loop Sell ticket while (t Rue) {synchronized (this) {if (Ticket > 0) {try {thread.sleep (500); System.out.println (Thread.CurrentThread (). GetName () + "sell a ticket ..."); catch (Exception e) {e.printstacktrace ();} System.out.println ("Number of votes left:" +--ticket);} else {//The ticket has been sold out, the window stops the ticket break;}}}} public class Test001 {public static void main (string[] args) {//There are now three windows at the same time selling tickets MyThread r = new MyThread (); thread T1 = new Thread (r, "window One"); Thread t2 = new Thread (r, "window Two"); thread t3 = new Thread (r, "window three");//start concurrent selling ticket T1.start (); T2.start (); T3.start ();}}

The results of the program run as follows:

Window one sold a ticket ... Number of votes left: 9 window one sold a ticket ... Number of votes left: 8 window one sold a ticket ... Number of votes left: 7 window three sell a ticket ... Number of votes left: 6 window three sell a ticket ... Number of votes left: 5 window three sell a ticket ... Votes left: 4 window two sell a ticket ... Votes left: 3 window two sell a ticket ... Votes left: 2 window two sell a ticket ... Votes left: 1 window two sell a ticket ... Number of votes left: 0




Java Multi-Threading

Related Article

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.