Java multithreading: How to Create a thread?

Source: Internet
Author: User

Java multithreading: How to Create a thread?
In the previous article, we have already talked about the origins of processes and threads. Today we will talk about how to create a thread in Java and let the thread execute a subtask. The following describes concepts related to applications and processes in Java, and describes how to create threads and processes. The following is the directory outline of this article: 1. concepts related to applications and processes in Java 2. how to Create a thread in Java 3. if any errors occur in how to create a process in Java, please forgive me and welcome criticism and correction. 1. concepts related to applications and processes in Java (you can view them in the task manager in windows ). Java uses a single-thread programming model, that is, if we do not actively create a thread in our own program, we will only create one thread, which is usually called the main thread. However, although there is only one thread to execute the task, it does not mean that there is only one thread in the JVM. When a JVM instance is created, at the same time, many other threads (such as the Garbage Collector thread) will be created ). Java uses a single-thread programming model. Therefore, you must place time-consuming operations in the Child thread during UI programming to avoid blocking the main thread (during UI programming, the main thread is the UI thread used to process user interaction events ). 2. How to Create a Thread in Java if you want to create a Thread in java, there are generally two ways: 1) inherit the Thread class; 2) Implement the Runnable interface. 1. If the inherited Thread class inherits the Thread class, you must override the run method and define the task to be executed in the run method. Class MyThread extends Thread {private static int num = 0; public MyThread () {num ++ ;}@ Override public void run () {System. out. println ("actively created" + num + "Thread");} after creating your own Thread class, you can create a thread object, and then start () method to start the thread. Note: instead of calling the run () method to start the thread, the run method only defines the task to be executed. If the run method is called, it is equivalent to executing the run method in the main thread, there is no difference from a normal method call. At this time, a new thread is not created to execute 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 ("actively created" + num + "Thread") ;}} in the code above, a new thread will be created by calling the start () method. To distinguish the call of the start () method from the call of the run () method, see 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 publi C void run () {System. out. println ("name:" + name + "sub-Thread ID:" + Thread. currentThread (). getId () ;}} running result: the following conclusions can be drawn from the output result: 1) thread1 and thread2 have different thread IDs. thread2 and main thread IDs are the same, it means that the call through the run method does not create a new thread, but directly runs the run method in the main thread, which is no different from the normal method call; 2) although the start method of thread1 is called before the run method of thread2, the information about the run method call of thread2 is first output, it indicates that the process of creating a new thread does not block subsequent execution of the main thread. 2. Implement the Runnable interface to create a Thread in Java. In addition to inheriting the Thread class, you can also implement similar functions by implementing the Runnable interface. To implement the Runnable interface, you must override its run method. The following 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 ("sub-Thread ID:" + Thread. currentThread (). getId () ;}} the Chinese meaning of Runnable is "Ren As the name implies, by implementing the Runnable interface, we define a subtask and then hand it over to the Thread for execution. Note: In this method, Runnable must be used as a parameter of the Thread class, and a new Thread must be created through the Thread start method to execute this subtask. If you call the Runnable run method, it will not create a new thread. There is no difference in calling this normal method. In fact, looking at the implementation source code of the Thread class, we will find that the Thread class implements the Runnable interface. In Java, both methods can be used to create threads to execute subtasks. The specific method depends on your needs. Directly inheriting the Thread class may seem more concise than implementing the Runnable interface. However, since Java only allows single inheritance, if the custom class needs to inherit other classes, you can only choose to implement the Runnable interface. 3. How to create a process in Java can be created in two ways, involving a total of five main classes. The first method is to create a process using the runtime.exe c () method. The second method is to create a process using the start method of ProcessBuilder. The following describes the differences and connections between the two methods. The first thing to talk about is the Process class. The Process class is an abstract class. There are several abstract methods in it. You can find the source code of the Process class that is located in java. lang. under the Process path: public abstract class Process {abstract public OutputStream getOutputStream (); // obtain the output stream of the Process abstract public InputStream getInputStream (); // obtain the process input stream abstract public InputStream getErrorStream (); // obtain the process error stream abstract public int waitFor () throws InterruptedException; // wait for the process to abstract public int exitValue (); // get Abstract public void destroy (); // destroy process} 1) process ProcessBuilder is a final class, which 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;} pu Blic ProcessBuilder (String... command) {this. command = new ArrayList <String> (command. length); for (String arg: command) this. command. add (arg );}....} the constructor passes the command parameters of the process to be created. The first constructor puts the command parameters in the List and transmits them in the form of an indefinite string. Next, let's look at it. we mentioned that the start method of ProcessBuilder is used to create a new process. Let's take a look at the specific things in the start method. The specific implementation source code of the start method is as follows: public Process start () throws IOException {// Must convert to array first -- a malicious 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 emptyString prog = cmdarray [0]; Secu RityManager 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 much 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) ;}} this method returns a Process object. The first part of this method is equivalent to setting parameters based on command parameters and the set working directory, the most important thing is the return ProcessImpl in the try statement block. start (cmdarray, environment, dir, redirectErrorStream); this statement is used to create a process. Note that the start method of the ProcessImpl class is called, here we can know that start is a static method. So what kind of ProcessImpl is? This class is also located in java. lang. under the ProcessImpl path, let's take a look at the specific implementation of this 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 start (String cmdarray [], java. util. map <String, String> environment, String dir, boolean redirectErrorStream) throws IOException {String envblock = ProcessEnvironment. toEnvironmentBlock (environment); return new P RocessImpl (cmdarray, envblock, dir, redirectErrorStream );}....} this is the specific implementation of the start method of the ProcessImpl class. In fact, the start method creates a ProcessImpl object through this sentence: 1 return new ProcessImpl (cmdarray, envblock, dir, redirectErrorStream ); several abstract methods in the Process class are implemented in ProcessImpl. In fact, the start method of ProcessBuilder is used to create a ProcessImpl object. The following is an example of creating a process using ProcessBuilder. For example, if you want to start a process using ProcessBuilder to open cmd and obtain the IP address information, you can write it like this: public class Test {public static void main (String [] args) throws IOException {ProcessBuilder pb = new ProcessBuilder ("cmd", "/c", "ipconfig/all "); process process = pb. start (); begin transaction = new transaction (process. getInputStream (); while (partial. hasNextLine () {System. out. println (bytes. nextLine ();} seconds. clo Se () ;}} The first step is the most critical. It is to pass the command string to the constructor of ProcessBuilder. Generally, each independent command in the string is used as a separate parameter, however, you can also put them in the List in order. Many other specific usage are not described here. For example, you can use the environment method of ProcessBuilder and File directory to set the environment variables and working directories of processes, if you are interested, you can view the relevant API documentation. 2) use the exec method of Runtime to create a process. First, let's take a look at the specific implementation of the Runtime class and exec method. Runtime, as its name suggests, indicates the Virtual Machine instance where the current process is located. Since any process only runs in one virtual machine instance, the Runtime adopts the singleton mode, that is, only one virtual machine instance is generated: 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 be invoked with respect to the current runtime object. ** @ return the <code> Runtime </code> object associ Ated 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 this that the Runtime class constructor is private, so only the Runtime instance can be obtained through getRuntime. Next, let's take a look at the exec method implementation. In Runtime, there are multiple exec different overload implementations, but the final execution is the exec method of this version: public Process exec (String [] cmdarray, string [] envp, File dir) throws IOException {return new ProcessBuilder (cmdarray ). environment (envp ). directory (dir ). start ();} can be found that, in fact, if you create a process through the exec of the Runtime class, it is finally created through the start method of the ProcessBuilder class. Let's take a look at an example. Let's take a look at how to create a process through Runtime exec. In the previous example, call cmd to obtain IP address information: public class Test {public static void main (String [] args) throws IOException {String cmd = "cmd" + "/c" + "ipconfig/all "; process process = runtime.getruntime(.exe c (cmd); worker = new worker (process. getInputStream (); while (partial. hasNextLine () {System. out. println (bytes. nextLine ();} seconds. close () ;}} note that the exec method does not support the variable length parameter (Pr OcessBuilder supports variable length parameters). Therefore, you must splice the command parameters before passing them in.

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.