Java multithreaded Programming (i) Java multithreading skills

Source: Internet
Author: User
Tags thread class

I. The concept of process and multithreading and the advantages of threading

Open Windo Task Manager can see a lot of running EXE program, fully can run in memory exe file as a process, the process is a basic operating unit managed by the OS.

Threads can be understood as subtasks that run independently in a process. For example, the QQ.exe runtime has many subtasks running at the same time.

Using threads, you can maximize the CPU's idle time to handle other tasks, and the CPU is constantly switching between characters, and because of the fast switching speed, people feel that these tasks seem to be running at the same time. In other words, you can run more different kinds of tasks at the same time, which can greatly increase the CPU utilization.

Second, the use of multi-threading

At least one thread is running when a process is running.

1  Package test; 2 3  Public class Test {45      Public Static void Main (string[] args) {6        System.out.println (Thread.CurrentThread (). GetName ()); 7     }89 }

The output is: main. The main output here is actually a thread named main that executes the code in the main () method.

1. Inheriting the thread class

There are two main ways to implement multithreaded programming: One is to inherit the thread class and the other is to implement the Runnable interface. Judging from the structure of the thread class, the thread class implements the Runnable interface, which has multiple relationships between them. In order to support multiple inheritance, it is possible to implement the form of the Runnable interface while inheriting one side.

1.1 The randomness of a thread's invocation

1  Public class extends Thread {2    @Override3public     void  run () {  4         Super. Run (); 5         System.out.println ("MyThread"); 6     }7 }
1  Packagetest;2 3 ImportCom.mythread.www.MyThread;4 5  Public classRun {6 7      Public Static voidMain (string[] args) {8MyThread MyThread =NewMyThread ();9 Mythread.start ();TenSystem.out.println ("End of Run"); One     } A  -}
Run End Mythread

As you can see from the output, the result of the code is unrelated to the order in which the code executes or the order in which it was called, and the thread is a subtask, and the CPU calls the Run method in the thread in an indeterminate way, or at random time.

1.2 Demonstrating the randomness of threads

1  PackageMythread;2 3  Public classMyThreadextendsThread {4 @Override5      Public voidrun () {6         Try {7              for(inti = 0; I < 10; i++) {8                 intTime = (int) (Math.random () * 1000);9 Thread.Sleep (time);TenSystem.out.println ("run=" +Thread.CurrentThread (). GetName ()); One             } A}Catch(interruptedexception e) { - e.printstacktrace (); -         } the     } -}
1  Packagetest;2 3 ImportMythread. MyThread;4 5  Public classTest {6      Public Static voidMain (string[] args) {7         Try {8 9MyThread thread =NewMyThread ();TenThread.setname ("MyThread"); One Thread.Start (); A  -              for(inti = 0; I < 10; i++) { -                 intTime = (int) (Math.random () * 1000); the Thread.Sleep (time); -System.out.println ("main=" +Thread.CurrentThread (). GetName ()); -             } -}Catch(interruptedexception e) { + e.printstacktrace (); -         } +     } A}
main=mainmain=mainrun=mythreadmain=mainrun=mythreadrun=mythreadmain=mainmain=mainrun=mythreadmain=mainmain= Mainrun=mythreadmain=mainmain=mainrun=mythreadrun=mythreadrun=mythreadmain=mainrun=mythreadrun=mythread

As can be seen from the output of the 20 results, the start () method in the Thread.java class notifies the thread planner that this thread is ready to wait for the run () method of the calling thread object. This process actually allows the system to schedule a time to invoke the run () method in thread, which is to make the thread run, start the thread, and have the effect of executing asynchronously.

1.3 Synchronous execution

If the call to the Thread.run () method is not asynchronous, but synchronous, then the thread object is not handed over to the thread planner for processing, but instead is invoked by the main main thread to call the run () method, which means that the code in the Run () method must be executed before the subsequent code can be executed.

1  PackageExtthread;2 3  Public classMyThreadextendsThread {4 5     Private inti;6 7      PublicMyThread (inti) {8         Super();9          This. i =i;Ten     } One  A @Override -      Public voidrun () { - System.out.println (i); the     } -  -}
1  Packagetest;2 3 ImportExtthread. MyThread;4 5  Public classTest {6 7      Public Static voidMain (string[] args) {8MyThread T11 =NewMyThread (1);9MyThread T12 =NewMyThread (2);TenMyThread t13 =NewMyThread (3); OneMyThread t14 =NewMyThread (4); AMyThread t15 =NewMyThread (5); -MyThread t16 =NewMyThread (6); -MyThread t17 =NewMyThread (7); theMyThread t18 =NewMyThread (8); -MyThread t19 =NewMyThread (9); -MyThread t110 =NewMyThread (10); -MyThread t111 =NewMyThread (11); +MyThread t112 =NewMyThread (12); -MyThread t113 =NewMyThread (13); +  A T11.start (); at T12.start (); - T13.start (); - T14.start (); - T15.start (); - T16.start (); - T17.start (); in T18.start (); - T19.start (); to T110.start (); + T111.start (); - T112.start (); the T113.start (); *  $     }Panax Notoginseng  -}
23145768109111213

As you can see from the output, the order of the start () method does not represent the order in which threads start.

2. Implement the Runnable interface

If you want to create a thread class that already has a parent class, you can no longer inherit from the thread class, because Java does not support multiple inheritance, so you need to implement the Runnable interface.

1  Package myrunnable; 2 3  Public class Implements Runnable {4    @Override5public     void  Run () {6         System.out.println ("run! in the Myrunnable class") ); 7     }8 }
1  Packagetest;2 3 Importmyrunnable. myrunnable;4 5  Public classRun {6 7      Public Static voidMain (string[] args) {8Runnable runnable=Newmyrunnable ();9Thread thread=NewThread (runnable);Ten Thread.Start (); OneSystem.out.println ("main! in Run"); A     } -  -}
run! in the Main!myrunnable class in run

In the 8 constructors of the Thread.java class, there are two objects that can pass the Runnable interface, and because the thread class also implements the Runnable interface, it also means that the constructor thread (Runnable target) Not only can you pass in an object that is an Runnable interface, but you can also pass in an object of the thread class, so that you can simply leave the run () method in a thread object to other threads for invocation.

3. Instance variables and thread safety

Instance variables in a custom thread class can have shared and unshared points for other threads.

3.1 Do not share data

3.2 Sharing data

4. Be aware of i--and System.out.println () anomalies

Third, CurrentThread () method

Iv. isAlive () method

V. Sleep () method

Vi. getId () method

Seven, stop the thread

1. Threads that can't be stopped

2. Determine if a thread is in a stopped state

3. Can stop the thread--exception method

4. Stop in slumber

5. The thread that can stop--the violence stops

6. Method Stop () and Java.lang.ThreadDeath exception

7. Bad consequences of releasing the lock

8. Use return to stop the thread

Eight, suspend thread

1.suspend and the use of the Resume method

2.suspend and the disadvantage of the resume method--monopoly

3.suspend and the disadvantage of the resume method--out of sync

Nine, Yield () method

X. Priority of Threads

1. Inheritance characteristics of thread precedence

2. Precedence is rule-

3. The precedence has randomness

4. See who runs fast

Xi. Daemon Thread

Java multithreaded Programming (i) Java multithreading skills

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.