Java Concurrent programming creation thread _java

Source: Internet
Author: User
Tags get ip thread class

Start with a description of the application and process-related concepts in Java, and then explain how to create a thread and how to create a process. The following is a table of contents outline for this article:

A. Java concepts related to application and process

Two. How to create a thread in Java

Three. How to create a process in Java

A. Java concepts related to application and process

In Java, an application corresponds to a JVM instance (also known as a JVM process), usually by default Java.exe or Javaw.exe (Windows can be viewed through Task Manager). Java uses a single-threaded programming model, in which a thread is created, often called the main thread, in our own program without the active creation of threads. Note, however, that while only one thread is performing the task, it does not mean that there is only one thread in the JVM, and many other threads (such as garbage collector threads) are created while the JVM instance is being created.

Because Java uses a single-threaded programming model, it is necessary to be careful in UI programming to place time-consuming operations in child threads to avoid blocking the main thread (the main thread, the UI thread, is used to handle user interaction events when the UI is programmed).

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. Inherit 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{
 private static int num = 0;
 
 Public Mythread () {
 num++;
 }
 
 @Override public
 Void Run () {
 System.out.println ("+num+") ("actively created first");
 }

Once you have created your own thread class, you can create the thread object and then start the thread through the start () method. Note that instead of invoking the run () method to start a thread, the Run method simply defines the task that needs to be performed, and if the Run method is called, which is equivalent to executing the Run method in the main thread, no difference is made to the normal method invocation, and no new thread is created to perform the defined task

public class Test {public
 static void Main (string[] args) {
 mythread thread = new Mythread ();
 Thread.Start ();
 }
 
Class Mythread extends thread{
 private static int num = 0;
 
 Public Mythread () {
 num++;
 }
 
 @Override public
 Void Run () {
 System.out.println ("+num+") ("actively created first");
 }

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

public class Test {public
 static void Main (string[] args) {
 System.out.println ("Main thread ID:" +thread.currentthread ( ). GetId ());
 Mythread thread1 = new Mythread ("Thread1");
 Thread1.start ();
 Mythread thread2 = new Mythread ("Thread2");
 Thread2.run ();
 }
 
Class Mythread extends thread{
 private String name;
 
 Public Mythread (String name) {
 this.name = name;
 }
 
 @Override public
 Void Run () {
 System.out.println ("Name:" +name+ "Child thread ID:" +thread.currentthread (). GetId ());
 }
}

Run Result:

From the output results can draw the following conclusions:

1 Thread1 and thread2 have different thread IDs, thread2 and main thread IDs are the same, indicating that a new thread is not created by invoking the Run method, but rather that the run method runs directly in the main thread without any distinction 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, which means that the process created by the new thread does not block subsequent execution of the main thread.

2. Implement 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 void Main (string[] args) {
 System.out.println ("Main thread ID:" +thread.currentthread ( ). GetId ());
 Myrunnable runnable = new myrunnable ();
 Thread thread = new Thread (runnable);
 Thread.Start ();
 }
 
Class Myrunnable implements runnable{public
 
 myrunnable () {
 
 }
 
 @Override public
 void Run () {
 SYSTEM.OUT.PRINTLN ("Child thread ID:" +thread.currentthread (). GetId ());
 }

Runnable's Chinese meaning is "task", as the name suggests, by implementing the Runnable interface, we define a subtask and then leave the subtasks to thread to execute. Note that this method must use runnable as a parameter to the thread class, and then create a new thread through the thread's Start method to perform the child task. If you call the Runnable run method, you will not create a new thread, and this normal method call does not make any difference.

In fact, viewing the implementation source code of the thread class discovers that the thread class implements the Runnable interface.

In Java, these 2 ways can be used to create threads to perform subtasks, depending on your needs. Inheriting the thread class directly may seem simpler than implementing the Runnable interface, but because 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 major classes.

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

The first thing to talk about is the process class, the process class is an abstract class, in which there are mainly several abstract methods, which can be viewed by the source code of the Process class:

Located under java.lang.Process path:

public class Test {public
 static void Main (string[] args) {
 System.out.println ("Main thread ID:" +thread.currentthread ( ). GetId ());
 Myrunnable runnable = new myrunnable ();
 Thread thread = new Thread (runnable);
 Thread.Start ();
 }
 
Class Myrunnable implements runnable{public
 
 myrunnable () {
 
 }
 
 @Override public
 void Run () {
 SYSTEM.OUT.PRINTLN ("Child thread ID:" +thread.currentthread (). GetId ());
 }

1 Create process through Processbuilder

Processbuilder is a final class that has two constructors:

Public final class Processbuilder
{
 private list<string> command;
 Private File directory;
 Private map<string,string> environment;
 Private Boolean redirecterrorstream;
 
 Public processbuilder (list<string> command) {
 if (command = null)
 throw new NullPointerException ();
 This.command = command;
 
 Public Processbuilder (String ... command) {
 This.command = new arraylist<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, the first constructor takes the command arguments into the list, and the second constructor is passed in as an indefinite string.

So let's look at the previous mention of creating a new process through the Processbuilder start method, and let's look at what's going on in the Start method. The following is the specific implementation source code for the Start method:

 public Process start () throws IOException {//must convert to array-a Maliciou
s user-supplied//list might try to circumvent the security check.
string[] Cmdarray = Command.toarray (New string[command.size ());
for (String Arg:cmdarray) if (arg = = null) throw new NullPointerException ();
 
Throws indexoutofboundsexception if command is empty String prog = cmdarray[0];
SecurityManager security = System.getsecuritymanager ();
 
if (security!= null) security.checkexec (prog); String dir = Directory = null?
 
Null:directory.toString (); try {return Processimpl.start (Cmdarray, Environment, dir, Redirecterrorstream);} catch (IOException e) {//It ' s MU
 CH easier for us to create a high-quality error//message than the low-level C code which found the problem. throw new IOException ("Cannot run program \" "+ prog +" \ "+ (dir = null?) "": "(in Directory \" "+ dir +" \ ")") + ":" + e.getmessage (), e);} 

The method returns a Process object that is equivalent to a parameter setting based on the command parameters and the working directory that is set up, and most importantly, the sentence in the TRY statement block:

Return Processimpl.start (Cmdarray,
 Environment,
 dir,
 Redirecterrorstream);

This is the sentence that really creates the process, and note that the start method of the Processimpl class is invoked, where it is necessary to know that start is 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:

Final class Processimpl extends process {
 
 //system-dependent portion of Processbuilder.start ()
 Static Process St Art (String cmdarray[],
 java.util.map<string,string> environment,
 string dir,
 Boolean Redirecterrorstream)
 throws IOException
 {
 String envblock = Processenvironment.toenvironmentblock ( environment);
 return new Processimpl (Cmdarray, Envblock, dir, redirecterrorstream);
 }
 ....
}

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

Return to New Processimpl (Cmdarray, Envblock, dir, Redirecterrorstream);
In Processimpl, several abstract methods in the process class are implemented concretely.

Explains that a Processimpl object is actually created by the Processbuilder start method.

Let's take a look at the example of using Processbuilder to create a process, such as I'm going to start a process via Processbuilder to open cmd and get IP address information, so write:

public class Test {public
 static void Main (string[] args) throws IOException {
 Processbuilder PB = new Processbui Lder ("cmd", "/C", "Ipconfig/all");
 Process process = Pb.start ();
 Scanner Scanner = new Scanner (Process.getinputstream ());
 
 while (Scanner.hasnextline ()) {
 System.out.println (Scanner.nextline ());
 }
 Scanner.close ();
 }

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

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

2 to create a process through the runtime Exec method

First, let's take a look at the concrete implementation of the Runtime class and Exec method, Runtime, as the name suggests, that is, the runtime, which represents the virtual machine instance where the current process resides.

Because any process runs only in one virtual machine instance, a singleton pattern is used in runtime, which only produces one instance of the virtual machine:

public class Runtime {
 private static Runtime currentruntime = new Runtime ();
 
 /**
 * Returns The runtime object associated with the current Java application.
 * Most of the methods of class <code>Runtime</code> are instance
 * methods and must are invoked with Respec T to the current runtime object.
 *
 @return The <code>Runtime</code> object associated with the current
 * Java application.
 *
 /public static Runtime GetRuntime () {return
 currentruntime;
 }
 
 /** Don ' t let anyone else instantiate this class *
 /Private Runtime () {}
 ...
 }

It can be seen from here that, because the constructor of the runtime class is private, it is only through GetRuntime to get the runtime instance. Next, look at the Exec method implementation, there are multiple exec implementations in runtime, but this version of the Exec method is really final:

Public Process exec (string[] cmdarray, string[] envp, File dir)
 throws IOException {return
 new Processbuilder (cm Darray)
 . Environment (ENVP).
 directory (dir)
 . Start ();
 }

It can be found that, in fact, through the exec creation process of the runtime class, it is ultimately created by the start method of the Processbuilder class.

Let's look at an example of how to create a process through runtime exec, or the previous example, call cmd, get the IP address information:

public class Test {public
 static void Main (string[] args) throws IOException {
 String cmd = "cmd" + "C" + "ipconf" Ig/all ";
 Process process = Runtime.getruntime (). exec (cmd);
 Scanner Scanner = new Scanner (Process.getinputstream ());
 
 while (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 for indefinite length parameters), so the command parameters must be spliced before being passed in.

As for how to create threads and processes in Java, so much for the time being, interested friends can refer to the relevant information.

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.