gpt4 book ai didi

java - 多线程程序和操作系统进程

转载 作者:行者123 更新时间:2023-12-02 12:10:40 27 4
gpt4 key购买 nike

我在 Kathy Sierra 撰写的 OCA 准备书中看到了这句话。我假设当使用 jvm 运行我的 java 程序时,它运行单个操作系统进程。我猜我运行的程序就是由这个进程执行的。如果这是真的,那么java程序如何使用许多操作系统进程呢?

Multithreaded Java provides built-in language features and APIs that allow programs to use many operating-system processes (hence, many “cores”) at the same time.

最佳答案

进程独立运行并与其他进程隔离。它不能直接访问其他进程中的共享数据。进程的资源,例如内存和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

关于java - 多线程程序和操作系统进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46577182/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com