Java multithreaded Walkthrough (ii)------How to create processes and threads

Source: Internet
Author: User
Tags thread class

Java Multithreading (a) Introduction to------concept: http://www.cnblogs.com/ysocean/p/6882988.html

In the previous blog, we've covered the differences between concurrency and parallelism, and the understanding of processes and threads, so how do you create processes and threads in Java?

1. Create a process in the Windows operating system

In the Windows operating system, we create a process that usually opens an application, which creates a process on the computer. More primitive, we'll do it at the command prompt (let's take the process of opening Notepad as an example):

First step: windows+r, enter cmd, open cmd command prompt

      

Step Two: Enter Notepad at the command prompt and press ENTER to pop up the Notepad application

      

PS: Common Windows Application commands

1.regedit: open Registry Editor

2. Control : Open Control Panel

3. msconfig : Open System Configuration

4. gpedit.msc : Open Local Group Policy

5. Explorer : Open Resource Manager

6. taskmgr : Task Manager

7. Logoff : Log off the computer directly

8. Osk : Open the On- screen Keyboard

9. Calc : Open Calculator

10. MSPaint: Bring up drawing software

11. DxDiag : View computer Detailed configuration information

12. mstsc: Open Remote Desktop Connection

13. SystemInfo : View Basic Computer Information

14. Notepad: Open Notepad

      

2. Create a process in Java

The first method: Create a process from the Exec () method of the Runtime class

public class Runtimeextends Object
①, which represents the virtual machine instance where the current process resides, each Java application has a runtime class that allows the application to interface with the environment in which the application is run.
②, because any process will only run with one virtual machine instance, that will only produce a virtual machine instance (the underlying source is in singleton mode)
③, the current runtime can be obtained from the GetRuntime method.

As can be seen from the source code above, the constructor is privatized, that is, external we cannot new the runtime instance, and internally gives us a way to get the runtime instance GetRuntime ().

Create a Notepad process from the Runtime class

public class Processtest {public static void main (string[] args) throws Exception {Runtime run = runtime.getruntime ();//Open Notepad run.exec ("Notepad");}}

  

  

Second method: Create a thread from Processbuilder

Public final class Processbuilderextends Object

public class Processtest {public static void main (string[] args) throws Exception {//Open Notepad processbuilder pBuilder = new Pr Ocessbuilder ("notepad");p Builder.start ();}}

  

  

3. Creating Threads in Java

The first method: Inherit the Thread class

public class Threadextends Objectimplements Runnable

Step: 1, define a thread Class A inherits from the Java.lang.Thread class

2. The run () method that covers the Thread class in Class A

3. Write the actions you want to perform in the Run () method

4. In the Main method (thread), create the Thread object and start the thread

Create thread class: Class A = new A () class;

Call the Start () method to launch the thread: A.start ();

Package Com.ys.thread;class Thread1 extends thread{@Overridepublic void Run () {for (int i = 0; i <; i++) {System.out. println ("Play Music" +i);}}} public class ThreadTest {public static void main (string[] args) {for (int i = 0; i <; i++) {System.out.println ("Play The Game" +i), if (i==5) {Thread1 Th1 = new Thread1 (); Th1.start ();}}}

Results:

Play games 0 play Games 1 play games 2 play Games 3 play Games 4 play games 5 play games 6 play games 7 play games 8 play the game 9 play Music 0 play Music 1 play Music 2 play Music 3 play Music 4 play Music 5 play Music

Note: We look at the results, not 5 first hit the game, and then play the music, this is the result of the thread scheduling, two threads at the same time in the scramble for CPU resources, that is, the final result, the first 5 dozen games must appear, the back of the time when the play music to see how the CPU dispatch, this is random. We can't interfere.

Second approach: Implement the Runnable interface

@FunctionalInterfacepublic Interface Runnable

  

1. The runnable interface should be implemented by any class and its instance will be executed by the thread. The class must define a method that has no parameters, called run.
2. This interface is intended to provide a common protocol for objects that want to execute code at activity time. This class has only one run () abstract method

Step: 1, define a thread class A implemented on the Java.lang.Runnable interface (Note: Class A is not a thread class, there is no start () method, the thread cannot be started directly from an instance of new a)

2. The run () method that covers the Runnable interface in class A

3. Write the actions you want to perform in the Run () method

4. In the Main method (thread), create the Thread object and start the thread

Create thread classes: thread t = new Thread (new Class A ());

Call the Start () method to launch the thread: T.start ();

Class Runnable1 implements runnable{@Overridepublic void Run () {for (int i = 0; i <; i++) {System.out.println ("Play Music" + i);}}} public class Runnabletest {public static void main (string[] args) {for (int i = 0; i <; i++) {System.out.println ("Play Tour +i), if (i==5) {Thread Th1 = new Thread (new Runnable1 ()); Th1.start ();}}}

  

Third method: Create a thread with an anonymous inner class

public static void Main (string[] args) {for (int i = 0; i < i++) {System.out.println ("Play the Game" +i); if (i==5) {New Thread (n EW Runnable () {@Overridepublic void Run () {for (int i = 0; i <; i++) {System.out.println ("Play Music" +i);}}). Start ();}}}

  

Attention:

1. The startup thread is calling the start () method instead of calling the run () method.

Parse: Run () method: Call the Run () method within this thread, and the other methods are no different, can be repeated multiple calls;

Start () method: Starts a thread and actually calls the run () method of the Runnable object.

Open the Thread class source code, the start () method has a sentence:

Private native void Start0 (); Native Keyword: Local program call

The native keyword refers to the Java local interface call, which is the function function that calls the local operating system using Java to do some special operations, and such code development in Java almost rarely occurs, because Java is the greatest feature of portability, if a program Can only be used on a fixed operating system, then the portability will be completely lost, multi-threaded implementation must be supported by the operating system, then the Start0 () method is actually very similar to the abstract method, there is no method body, but to the JVM to achieve, That is, the JVM under Windows may use the A method to implement Start0 (), the JVM under Linux may use the B method to implement Start0 (), at the time of the call does not care how the specific way to implement the Start0 () method, will only care about the final operation results, to The JVM went to match the different operating systems.

2, can not start the same thread multiple times, that is, multiple calls to start () method, can only be called once, or error:

  

Java multithreaded Walkthrough (ii)------How to create processes and threads

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.