Java Concurrent Programming: threading, Process creation

Source: Internet
Author: User
Tags get ip

The process, threading, and application concepts need to be cleared first.
In a sense, a process is a process that an application performs on a processing machine, which is a dynamic concept, and a thread is a part of a process that contains multiple threads running.

A
A process is a run-time activity of a program with independent functionality about a data collection. It can apply and own system resources, is a dynamic concept, is an active entity. It is not just the code of the program, it also includes the current activity, which is represented by the value of the program counter and the contents of the processing register.

B
A process is an "executing program". A program is an inanimate entity that can become an active entity when the processor is given the program's life, which we call a process.

C
Typically, you can include several threads in a process that can take advantage of the resources owned by the process. In the operating system in which threading is introduced, the process is usually used as the basic unit for allocating resources, while threads are used as the basic unit of independent operation and independent Dispatch. Because the thread is smaller than the process, and basically does not have the system resources, the cost of its scheduling will be much smaller, can be more efficient to improve the degree of concurrent execution among the multiple programs within the system.

D
The difference between a thread and a process is that the child process and the parent process have different code and data spaces, while multiple threads share the data space, and each thread has its own execution stack and program counter for its execution context. Multithreading is mainly to save CPU time, play use, depending on the situation. The running of a thread requires the use of the computer's memory resources and CPU.

E
The difference between threads and processes is summarized:
A. address space and other resources : processes are independent of each other and are shared among threads of the same process. Threads within a process are not visible in other processes.
B. communication : Inter-process communication IPC, between threads can directly read and write process data segments (such as global variables) to communicate--requires process synchronization and mutual exclusion means of support to ensure data consistency.
C. scheduling and switching : Thread context switches are much faster than process context switches.
D. In a multithreaded OS, a process is not an executable entity.

F

A process is a program with a certain independent function about a single run activity on a data set, a process that is an independent unit of the system's resource allocation and scheduling. A thread is an entity of a process that is the basic unit of CPU dispatch and dispatch, which is a smaller unit that can run independently than a process. The thread itself does not own the system resources, it has only a few resources (such as program counters, a set of registers and stacks) that are essential in the run, but it can share all the resources owned by the process with other threads belonging to one process.

A process is a run-time activity of a program with independent functionality about a data collection. It can apply and own system resources, is a dynamic concept, is an active entity. It is not just the code of the program, it also includes the current activity, which is represented by the value of the program counter and the contents of the processing register.
In Java, an application corresponds to a JVM instance (also known as a JVM process), with the general name default Java.exe or Javaw.exe (Windows can be viewed through Task Manager). Java uses a single-threaded programming model in which, in our own programs, only one thread is created, often called the main thread, if the thread is not actively created. Note, however, that while there is only one thread to perform the task, it does not mean that there is only one thread in the JVM, and when the JVM instance is created, many other threads (such as the garbage collector thread) are created.

Because Java uses a single-threaded programming model, it is important to be aware of the need to place time-consuming operations on child threads in UI programming to avoid blocking the main thread (in UI programming, the main thread is the UI thread, which handles user interaction events).

Two. How to create a thread in Java

In Java if you want to create a thread, there are generally two ways: 1) inherit the thread class; 2) Implement the Runnable interface.

1. Inheriting the thread class

If you inherit the thread class, you must override the Run method to define the tasks that need to be performed in the Run method.

class MyThread extends Thread{privatestaticint0publicpublicvoid run() { System.out.println("主动创建的第"+num+"个线程"); }}

Once you have created your own thread class, you can create a thread object and then start the thread with the start () method. Note that instead of calling the run () method to start the thread, the Run method simply defines the task that needs to be performed, and if calling the Run method, which is equivalent to executing the Run method in the main thread, is no different from the normal method call, and does not create a new thread to perform the defined task.

 Public  class Test {  Public Static voidMain (string[] args) {MyThread thread =NewMyThread (); Thread.Start (); }} class MyThread extends Thread{ Private Static intnum =0; PublicMyThread () {num++;} @Override Public voidRun () {System.out.println ("actively created first"+num+a "thread"); }}

In the code above, a new thread is created by invoking the start () method. To distinguish between the start () method call and the run () method call, consider the following example:

 Public  class Test {  Public Static voidMain (string[] args) {System.out.println ("Main thread ID:"+thread.currentthread (). GetId ()); MyThread Thread1 =NewMyThread ("Thread1"); Thread1.start (); MyThread thread2 =NewMyThread ("Thread2"); Thread2.run (); }} class MyThread extends Thread{ PrivateString name; PublicMyThread (String name) { This. name = name; } @Override Public voidRun () {System.out.println ("Name:"+name+"Child thread ID:"+thread.currentthread (). GetId ()); }}

Operation Result:

The following conclusions can be drawn from the output:

1) The thread IDs of Thread1 and Thread2 are different, and the thread2 and the main thread IDs are the same, stating that the Run method call does not create a new thread, but rather runs the run method directly in the main thread, without any difference from the normal method invocation;

2) Although the Thread1 start method call is called before the Thread2 Run method, the first output is information about the Thread2 Run method call, stating that the process created by the new thread does not block subsequent executions of the main thread.

2. Implement the Runnable interface

Creating Threads in Java In addition to inheriting the thread class, you can implement similar functionality by implementing the Runnable interface. Implementing the Runnable interface must override its Run method.

Here is an example:

 Public  class Test {  Public Static voidMain (string[] args) {System.out.println ("Main thread ID:"+thread.currentthread (). GetId ()); Myrunnable runnable =NewMyrunnable (); Thread thread =NewThread (runnable); Thread.Start (); }} class myrunnable implements Runnable{  PublicMyrunnable () {} @Override Public voidRun () {System.out.println ("Child thread ID:"+thread.currentthread (). GetId ()); }}

runnable Chinese means "task", as the name implies, by implementing the Runnable interface, we define a sub-task, and then leave the subtasks to thread to execute. Note that this method must use runnable as the parameter of the thread class, and then create a new thread to execute the subtask by using the thread's Start method. If you call Runnable's Run method, you will not create a new thread, and this common method call is no different.

In fact, looking at the implementation source code of the thread class will find that the thread class implements the Runnable interface.

In Java, these 2 ways can be used to create threads to perform subtasks, depending on which way to look at their own needs. Inheriting the thread class directly may seem more concise than implementing the Runnable interface, but since Java allows only single inheritance, you can only choose to implement the Runnable interface if the custom class needs to inherit other classes.

Three. How to create a process in Java

In Java, there are two ways to create a process, involving a total of 5 primary classes.

The first approach is to create a process through the runtime.exec () method, and the second is to create the process through the Processbuilder start method. Here's a talk about the differences and connections between the 2 ways.

The first thing to say is the process class, the process class is an abstract class, in which there are a few abstract methods, which can be viewed by looking at the source code of the Process class:
Located under the java.lang.Process path:

 Public Abstract classprocess{Abstract  PublicOutputStreamGetoutputstream();//Gets the output stream of the process Abstract  PublicInputStreamgetInputStream();//Gets the input stream of the process Abstract  PublicInputStreamGeterrorstream();//Gets the error stream of the process Abstract  Public int WaitFor() throws Interruptedexception;//Let process wait Abstract  Public int Exitvalue();//Get exit flag for the process Abstract  Public void Destroy();//Destroy process}

1) Create a process from Processbuilder

Processbuilder is a final class that has two constructors:

 Public Final  class processbuilder{ Privatelist<string> command;PrivateFile directory;PrivateMap<string,string> environment;Private BooleanRedirecterrorstream; Public Processbuilder(list<string> command) {if(Command = =NULL)Throw NewNullPointerException (); This. command = command; } Public Processbuilder(String ... command) { This. Command =NewArraylist<string> (command.length); for(String Arg:command) This. Command.add (ARG); }....}

The constructor passes the command arguments of the process that needs to be created, and the first constructor passes the command arguments into the list, and the second constructor is passed in the form of an indefinite long string.

So let's move on and look at the Processbuilder start method to create a new process, and we'll look at what we've done in the Start method. Here is the specific implementation of the Start method source code:

Public Process Start () throws IOException {String[] Cmdarray = Command.toarray (New String[Command.size ()]); for(StringArg:cmdarray)if(arg = =NULL)Throw NewNullPointerException ();StringProg = cmdarray[0]; SecurityManager security = System.getsecuritymanager ();if(Security! =NULL) security.checkexec (Prog);Stringdir = Directory = =NULL?NULL: Directory.tostring ();Try{returnProcessimpl.start (Cmdarray, Environment, dir, Redirecterrorstream);}Catch(IOException e) {Throw NewIOException (" cannot run program \" "+ Prog +"\""+ (dir = =NULL?"":"(in Directory \" "+ dir +"\")") +": "+ E.getmessage (), E); }}

The method returns a Process object, which is equivalent to some parameter settings based on the command parameters and the working directory set, and most importantly the sentence inside the TRY statement block:

returndir, redirectErrorStream);

Note that this is the phrase that really creates the process, notice that the Start method of the Processimpl class is called, and here you know that start must be a static method. So what kind of processimpl is it? The class is also located under the Java.lang.ProcessImpl path, looking at the specific implementation of the class:

Processimpl is also a final class that inherits the Process class:

finalclass ProcessImpl extends Process {  // System-dependent portion of ProcessBuilder.start()staticbooleanreturnnew ProcessImpl(cmdarray, envblock, dir, redirectErrorStream); } ....}

This is the concrete implementation of the Start method of the Processimpl class, and in fact the start method creates a Processimpl object by this sentence:

1
return new Processimpl (Cmdarray, Envblock, dir, Redirecterrorstream);
In Processimpl, several abstract methods in the process class are implemented concretely.

Description The fact that a Processimpl object was created through the Processbuilder start method.

Here is an example of using Processbuilder to create a process, such as I want to start a process through Processbuilder to open cmd, and obtain IP address information, then you can write:

publicclasspublicstaticvoidmainnew ProcessBuilder("cmd","/c","ipconfig/all"newwhile(scanner.hasNextLine()){ System.out.println(scanner.nextLine()); } scanner.close(); }}

The first step is to pass the command string to the Processbuilder constructor, in general, each individual command in the string as a separate argument, but it can also be passed in the list in order.

For many other specific uses, such as setting environment variables for processes and working directories through Processbuilder's environment Method and directory (File directory), interested friends can view the relevant API documentation.

2) Create a process through the runtime Exec method

First, let's look at the implementation of the runtime class and Exec method, runtime, as the name implies, the runtime, which represents the virtual machine instance where the current process resides.

Since any process will only run in one instance of a virtual machine, a singleton mode is used in runtime, which results in only one instance of the virtual machine:

 Public  class Runtime { Private StaticRuntime Currentruntime =NewRuntime ();/** * Returns The runtime object associated with the current Java application. * Most of the methods of class <code >Runtime</code> is instance * methods and must is invoked with respect to the current Runtime object. * * @return The <code>Runtime</code> object associated with the current * Java application. */  Public StaticRuntimeGetRuntime() {returnCurrentruntime; }/** Don ' t let anyone else instantiate this class * / Private Runtime() {} ... }

As can be seen from here, because the runtime class constructor is private, so only through the getruntime to get runtime instance. The next step is to look at the Exec method implementation, which has several different overloads of exec in runtime, but what really ends up executing this version of the Exec method:

publicexecthrowsreturnnew ProcessBuilder(cmdarray) .environment(envp) .directory(dir) .start(); }

It can be found that, in fact, through the runtime class exec creation process, eventually through the Processbuilder class of the Start method to create.

Take a look at an example of how exec creates a process through runtime, or the previous example, invoking CMD to get IP address information:

publicclasspublicstaticvoidmain"cmd "+"/c "+"ipconfig/all"newwhile(scanner.hasNextLine()){ System.out.println(scanner.nextLine()); } scanner.close(); }}

It is important to note that the Exec method does not support indefinite length parameters (Processbuilder is supported by variable length parameters), so the command parameters must be spliced before being passed in.

about how to create threads and processes in Java, so much for the moment, interested friends can refer to the relevant information,

Resources:

http://luckykapok918.blog.163.com/blog/static/205865043201210272168556/

http://www.cnblogs.com/ChrisWang/archive/2009/12/02/ Use-java-lang-process-and-processbuilder-to-create-native-application-process.html

http://lavasoft.blog.51cto.com/62575/15662/

The idea of Java programming

Java Concurrent Programming: threading, Process creation

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.