线程与进程

  在学习多线程之前,必须区分的一点是线程与进程。

  举个通俗易懂的例子。在电脑上打开迅雷,这就是一个进程,你再打开一个QQ,就又是一个进程;而你在迅雷上下载一部电影是一个线程(这里或许说的有错,迅雷下载一个

任务可能用到了许多线程,这里说得简单一点),同时你还可以再下载其他的东西,这又是一个线程。也就是说进程是系统上运行的一个程序,而线程是运行在一个程序中,并且系

统为每个进程分配单独的内存空间,而线程共享进程的一片存储空间。

--------------------------------------------------------------------------------------------------------------------------------------------------------------

  在理解了进程与线程之后,就该学习在程序中怎么创建自己的线程与进程了。

  首先看线程的创建:创建线程有两种方法——继承Thread和实现Runnable。

 1 public class cmd {
 2     public static void main(String[] args) throws IOException  {
 3         //创建线程只需newMyThread
 4         for(int i = 0;i<10;i++){
 5             MyThread thread = new MyThread(i);
 6             thread.start();
 7         }
 8     }
 9 }
10 //继承Thread
11 class MyThread extends Thread{
12     int i;
13     public MyThread(int i) {
14         this.i = i;
15     }
16     @Override
17     public void run() {
18         System.out.println("这是第"+i+"个线程"+Thread.currentThread().getName()); 
19     }
20 }
继承Thread
 1 public class cmd {
 2     public static void main(String[] args) throws IOException  {
 3         //实现Runnable创建线程
 4         for(int i = 0;i<10;i++){
 5             MyRunnable runnable = new MyRunnable(i);
 6             Thread thread = new Thread(runnable);
 7             thread.start();
 8         }
 9     }
10 }
11 
12 //实现Runnable
13 class MyRunnable implements Runnable{
14     int i;
15     public MyRunnable(int i) {
16         this.i = i;
17     }
18     public void run() {
19         System.out.println("这是第"+i+"个线程"+Thread.currentThread().getName()); 
20     }
21     
22 }
实现Runnable

-------------------------------------------------------------------------------------------------------------------------------------------------------------- 

  可以看出创建线程很简单,下面再来看怎么创建进程。

  创建进程也有两种方法:用Runtime.exec()和ProcessBuilder.start()。

1 public class cmd {
2     public static void main(String[] args) throws IOException  {
3         Runtime runtime = Runtime.getRuntime();
4         //调用exec方法在桌面创建一个记事本,其中"notepad.exe aaa"表示打开一个名为aaa的记事本,null为环境参数
5         //为null就表示继承父线程的环境参数,new File("C:\Users\ZY\Desktop")为工作目录,即在哪里创建记事本
6         
7         runtime.exec("notepad.exe aaa",null,new File("C:\Users\ZY\Desktop"));
8     }
9 }
Runtime
1 public class cmd {
2     public static void main(String[] args) throws IOException  {
3         ProcessBuilder bu = new ProcessBuilder("notepad.exe","aaa");
4         bu.directory(new File("C:\Users\ZY\Desktop"));
5         bu.start();
6     }
7 }
ProcessBuilder

  至此,创建进程的工作就完成了。

------------------------------------------------------------------------------------------------------------------------------------------------------------

待补充:从源码的角度去理解Runtime、ProcessBuilder

原文地址:https://www.cnblogs.com/Jc-zhu/p/4425538.html