Java Concurrency: How to create a thread (rpm)

Transfer from: http: //www.cnblogs.com/dolphin0520/p/3913517.html

The concept of a .Java regarding applications and processes related

  In Java, an application corresponds to a JVM instance (also known as a place JVM process), in general, the default is the name of java.exe or javaw.exe (the windows can be viewed through the Task Manager). Java uses a single-threaded programming model, that is, if not actively creating a thread, it will only create a thread in our own program, commonly referred to as the main thread. Note, however, although only one thread to perform the task, does not mean that only one thread in the JVM, JVM instances when it is created, and it will create a lot of other threads (such as garbage collection thread).

  Since Java programming model uses a single-threaded, so to be noted that during the time-consuming operation UI programmed in for the child thread, the main thread to avoid blocking (when the UI program, i.e. the main thread UI thread, for processing user interaction event).

How to create threads in two .Java

  In java if you want to create a thread, then there are two ways: 1) inherit the Thread class; 2) implement Runnable.

  1. Thread class inheritance

  Thread class inheritance, you must override the run method, define the task to be performed in the run method.

class the MyThread the extends the Thread {
     Private  static  int NUM = 0 ; 
     
    public the MyThread () { 
        NUM ++ ; 
    } 
     
    @Override 
    public  void RUN () { 
        System.out.println ( "second active created" + num + "threads" ); 
    } 
}

   Once you've created a class of its own thread, you can create a thread object, and then to start a thread through the start () method. Note that, instead of calling the run () method to start a thread, run method just defined tasks to be performed, if you call the run method, which is equivalent to execute the run method on the main thread, with the ordinary method calls without any distinction, not this time It creates a new thread to execute defined tasks.

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+"个线程");
    }
}

   In the above code, by calling the start () method will create a new thread up. In order to distinguish the start () method and calls the run () method call distinction, a look at the following example:

public class Test {
    public static void main(String[] args)  {
        System.out.println("主线程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+" 子线程ID:"+Thread.currentThread().getId());
    }
}

   operation result:

  From the output we can draw the following conclusions:

  1) thread1 and thread ID thread2 different, and the same thread2 main thread ID, description by calling the run method does not create a new thread, but run run method directly in the main thread, with the ordinary method call does not make any difference;

  2) Although thread1 the start in front of thread2 method calls the run method calls, but the output is the first information about the run method thread2 calls, explain the process to create a new thread does not block the subsequent execution of the main thread.

  2. implement Runnable

  Create threads in Java than in addition to inheriting the Thread class, you can also achieve similar functionality by implementing Runnable interface. Implement Runnable whose run method must be rewritten.

Below is an example:

public class Test {
    public static void main(String[] args)  {
        System.out.println("主线程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("子线程ID:"+Thread.currentThread().getId());
    }
}

   Runnable in Chinese means "mission", as the name suggests, by implementing Runnable interface, we define a sub-task, then the task will be handed over to child Thread execution. Note that, in this way must be Runnable Thread class as an argument, and then to create a new thread by Thread start method to perform the subtasks. If you call the Runnable's run method, then, it is not to create a new thread, which is the root of the ordinary method call does not make any difference.

  In fact, the view of the Thread class source code will find the Thread class is to achieve Runnable interface.

  In Java, these two methods can be used to create a thread to perform sub-tasks, the specific choice of which way to look at their needs. The direct successor Thread class, it may look more compact than implement Runnable, but because Java allows only single inheritance, so if the custom class needs to inherit from other classes, you can only choose to implement Runnable interface.

How to create a process in three .Java

   In Java, you can create a process in two ways, involving a total of five major categories.

  The first way is to create a process by Runtime.exec () method, the second method is to create a process by the start of the methods ProcessBuilder. Here to talk about differences and connections between these two methods.

  First talk about the Process class, the Process class is an abstract class, there are several major abstract method in it, this can be learned by looking at the source code of the Process class:

  Java.lang.Process located in the path:

public  abstract  class Process 
{ 
    
    abstract  public the OutputStream the getOutputStream ();    // get the process output stream 
      
    abstract  public the InputStream the getInputStream ();     // get the input process stream 
 
    abstract  public the InputStream getErrorStream ();    // get the process flow of the error 
 
    abstract  public  int waitFor () throws InterruptedException;    // let the process waits 
  
    abstract  public  int exitValue ();    // get the process of exit signs 
 
    abstract  public  void the destroy ();    //Destroying process 
}

  1) create a process by ProcessBuilder

  ProcessBuilder is a final class, it 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 is passed in command of the process parameters need to be created, the first constructor is a command parameter into the List which pass in the second constructor in the form of variable length strings passed into it.

  Then we read on, mentioned earlier is to create a new process by the start of the methods ProcessBuilder, we start to look at the specific method to do what to do. The following is a specific start method source code:

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 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 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, corresponds to the front part of the process parameters is set according to the command parameters and the working directory, the most important is inside a try block:

return ProcessImpl.start(cmdarray,
                    environment,
                    dir,
                    redirectErrorStream);

   The real explanation is that the process of creating an attention call is the start method ProcessImpl class, where you can start to know must be a static method. So ProcessImpl what is it like? This class also located under java.lang.ProcessImpl path, look at the concrete implementation of this class:

  ProcessImpl is a final class that inherits the Process category:

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 ProcessImpl(cmdarray, envblock, dir, redirectErrorStream);
    }
 ....
}

   This is a concrete realization of ProcessImpl class start method, and in fact the start method is to create a ProcessImpl object by the phrase:

return new ProcessImpl(cmdarray, envblock, dir, redirectErrorStream);

   In the several abstract methods ProcessImpl Process class concretely implemented.

  In fact description created by the start of the methods ProcessBuilder is a ProcessImpl object.

  The following look at an example of the process of creating ProcessBuilder specific use, such as I want to start a process to open cmd, and obtain information through ProcessBuilder ip address, you can write:

public class Test {
    public static void main(String[] args) throws IOException  {
        ProcessBuilder pb = new ProcessBuilder("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 the most critical, is to ProcessBuilder command string passed to the constructor, in general, is the string independently of each command as a single parameter, but can also be placed in order of List pass inside.

  As in many other specific usage does not repeat this conduct, such as setting environment variables and working directory of the process by the environment such as the methods and directory ProcessBuilder (File directory), and interested friends can view the API documentation.

  2) to create a process through exec method of Runtime

  Above all, look at the specific implementation and exec methods of class Runtime, Runtime, by definition, that is running, it indicates that the current process virtual machine instance is located.

  Since any process which will run in a virtual machine instance, the embodiment uses a single mode in Runtime, i.e. only produce a virtual machine instance:

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 associated with the current
     *          Java application.
     */
    public static Runtime getRuntime() {
    return currentRuntime;
    }
 
    /** Don't let anyone else instantiate this class */
    private Runtime() {}
    ...
 }

   As can be seen from this, since the Runtime class constructor is private, so only to acquire Runtime instance by getRuntime. Then look at the exec method to achieve focus, overloaded with multiple exec implementation in Runtime, but the real final performance of this version of the exec method:

public Process exec(String[] cmdarray, String[] envp, File dir)
   throws IOException {
   return new ProcessBuilder(cmdarray)
       .environment(envp)
       .directory(dir)
       .start();
   }

   Can be found, in fact, create a process through exec Runtime class, then eventually start to create a method by ProcessBuilder class.

  Let's look at an example, look at how to create a process by Runtime's exec, or the previous example, calling cmd, get ip address information:

public class Test {
    public static void main(String[] args) throws IOException  {
        String cmd = "cmd "+"/c "+"ipconfig/all";
        Process process = Runtime.getRuntime().exec(cmd);
        Scanner scanner = new Scanner(process.getInputStream());
         
        while(scanner.hasNextLine()){
            System.out.println(scanner.nextLine());
        }
        scanner.close();
    }
}

   Note that, exec method does not support variable length parameter (ProcessBuilder supports variable-length parameters), it must first re-transmission parameters for concatenated into good order.

  On how to create threads and processes in Java, then temporarily talk so much, interested friends can refer to the relevant information.

  References:

  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/

  "Java programming ideas"

Guess you like

Origin www.cnblogs.com/helios-fz/p/10932635.html