2017-10-05 65 views
0

我在由Kathy Sierra编写的OCA准备书中遇到了这个声明。我假设使用我的jvm运行我的java程序时,它运行一个OS进程。我猜我运行的程序是由这个过程执行的。如果这是真的,java程序如何使用许多操作系统进程?多线程程序和os进程

多线程Java提供了内置的语言功能和API 允许程序在同一时间使用多操作系统的过程(因此,许多 “核”)。

回答

1

一个进程独立运行并与其他进程隔离。它不能直接访问其他进程中的共享数据。该过程的资源,例如内存和CPU时间,通过操作系统分配给它。

线程是一个所谓的轻量级进程。它有自己的调用堆栈,但可以在同一进程中访问其他线程的共享数据。每个线程都有自己的内存缓存。如果一个线程读取共享数据,它将这些数据存储在它自己的内存缓存中。线程可以重新读取共享数据。

Java应用程序默认在一个进程中运行。在Java应用程序中,您可以使用多个线程来实现并行处理或异步行为。

例 下面是创建一个新的线程,并开始运行它的一个例子 -

class RunnableDemo implements Runnable { 
    private Thread t; 
    private String threadName; 

    RunnableDemo(String name) { 
     threadName = name; 
     System.out.println("Creating " + threadName); 
    } 

    public void run() { 
     System.out.println("Running " + threadName); 
     try { 
     for(int i = 4; i > 0; i--) { 
      System.out.println("Thread: " + threadName + ", " + i); 
      // Let the thread sleep for a while. 
      Thread.sleep(50); 
     } 
     }catch (InterruptedException e) { 
     System.out.println("Thread " + threadName + " interrupted."); 
     } 
     System.out.println("Thread " + threadName + " exiting."); 
    } 

    public void start() { 
     System.out.println("Starting " + threadName); 
     if (t == null) { 
     t = new Thread (this, threadName); 
     t.start(); 
     } 
    } 
} 

public class TestThread { 

    public static void main(String args[]) { 
     RunnableDemo R1 = new RunnableDemo("Thread-1"); 
     R1.start(); 

     RunnableDemo R2 = new RunnableDemo("Thread-2"); 
     R2.start(); 
    } 
} 

这将产生下面的结果 -

输出

Creating Thread-1 
Starting Thread-1 
Creating Thread-2 
Starting Thread-2 
Running Thread-1 
Thread: Thread-1, 4 
Running Thread-2 
Thread: Thread-2, 4 
Thread: Thread-1, 3 
Thread: Thread-2, 3 
Thread: Thread-1, 2 
Thread: Thread-2, 2 
Thread: Thread-1, 1 
Thread: Thread-2, 1 
Thread Thread-1 exiting. 
Thread Thread-2 exiting. 

[1] http://www.vogella.com/tutorials/JavaConcurrency/article.html

[2] https://www.tutorialspoint.com/java/java_multithreading.htm

+0

感谢凤凰。我猜想线程仍然在单个OS进程中运行。但是,文中陈述了“允许程序使用许多操作系统进程的API”。这是真的? –

+0

是的,那是真的。 – Pheonix

+0

每个线程是否转换为OS进程?我假设所有线程共享相同的操作系统进程 –