JAVA multithreading mechanism (I), java multithreading mechanism

Source: Internet
Author: User

JAVA multithreading mechanism (I), java multithreading mechanism

PS: I started to talk about JAVA again .. Some time ago, I completed HTML + CSS. It was boring to start writing the lab interface... The blog will be updated later!

Update JAVA first...

Multithreading (1)

Main Content

1. threads in JAVA

2. Use the Thread subclass to create a Thread

3. Use the Runnable interface

4. Understand thread concurrency

Process: A process is a dynamic execution process of the program. It corresponds to a complete process from code loading, execution to execution completion. This process is also a process.

From the process of development and extinction, simply put, it is a program. For example, if we open a browser, then this browser is loaded into our

In the operating system, it becomes a process. What is the thread? The thread is embedded in the process. A process can have multiple threads and can be browsed.

.. When we open a browser, We can browse the webpage or play music in the browser. You can also download files at the same time. So this

A browser process contains multiple threads.

1. JAVA thread

 

/***/Public class Demo_1_1 {public static void main (String [] args) {speakhello sh = new speakhello (); speaknihao sn = new speaknihao (); sh. start (); sn. start (); for (int I = 1; I <= 20; I ++) System. out. print ("Hello everyone" + I + "") ;}} class speakhello extends Thread {public void run () {for (int I = 1; I <= 20; I ++) System. out. print ("hello" + I + "") ;}} class speaknihao extends Thread {public void run () {for (int I = 1; I <20; I ++) system. out. print ("hello" + I + "");}}

 

The execution results of the above Code are random .. I randomly cut the image ..

The above result is that the speakhello thread executes first, then the main thread executes three times, then the speakhello executes, and so on. This is because the JVM knows that there are three threads,

The main thread and the three threads speakhello and speaknihao switch the CPU among the three threads, and the switching speed is also very fast. We cannot imagine

.. After all three threads are executed, the JVM will not reallocate the CPU...

2. Thread method creation Thread and Runnable interface creation Thread

Both the Thread method and Runnable can create threads, but it is more common to use the Runnable interface to override the run () method, rather than inheriting the Thread class to override run ()

The reason is that JAVA does not support multi-inheritance. After inheriting the Thread class, it cannot expand other classes again. Runnable belongs to the interface type, and one interface can have multiple classes.

Implementation.

The code above inherits the Thread class to overwrite the run () method to create a Thread.

Ticket Selling:

Public class ticket {public static void main (String [] args) {// three windows are started to sell tickets. windows s1 = new windows (); windows s2 = new windows (); windows s3 = new windows (); Thread t1 = new Thread (s1); Thread t2 = new Thread (s2); Thread t3 = new Thread (s3); t1.start (); t2.start (); t3.start () ;}} class windows implements Runnable {private int num = 100;
// Private static int num = 100; public void run () {while (true) {try {Thread. sleep (1000); // issue tickets every second} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace ();} if (num> 0) {System. out. println ("selling" + num + "tickets"); num -- ;}else {break ;}}}}

The above result shows that each window sells its own tickets, and num does not share the tickets, as if a window sells plane tickets.

The other is to sell train tickets, and the last window is to sell bus tickets. In short, each window is allocated with 100 tickets.

To sell ....

One way isMake some modifications to the code... For example, in the annotation section, change num to static,The three windows

The 100 tickets will be shared. Another way is to encapsulate num into an object, and then start three threads for sharing ..

 

Public class ticket1 {public static void main (String [] args) {sel s = new sel (); Thread t1 = new Thread (s ); thread t2 = new Thread (s); Thread t3 = new Thread (s); t1.start (); t2.start (); t3.start ();}} /* buy tickets */class sel implements Runnable {private int num = 50; public void run () {while (true) {if (num> 0) {try {Thread. sleep (1000);} catch (Exception e) {e. printStackTrace ();} System. out. println (Thread. currentThread (). getName () + "sales in progress" + num + "tickets" + num --);} else {break ;}}}}

 

The above code realizes that the 100 tickets are shared by the three windows, but if the above Code places the try-catch statement below the while LOOP

In this case, the thread will have an accident, and the problem will be that the same ticket has been sold for multiple times, and some tickets have not been sold yet, and may even be sold

0 tickets ..

So why? This is the problem caused by thread concurrency ......

 

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.