问题
In the below program,
//Producer - IO bound
public class FileCrawler implements Runnable{
private final BlockingQueue<File> fileQueue;
private final File root;
....
public void run(){
try{
crawl(root); // IO bound
}catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}
private void crawl(File root) throws InterruptedException{
File[] entries = root.listFiles(fileFilter);
...
for(File entry: entries){
fileQueue.put(entry);
}
}
}
//Consumer - CPU bound
public class Indexer implements Runnable{
private final BlockingQueue<File> queue;
....
public void run(){
try{
while(true){
indexFile(queue.take()); // CPU bound
}
}catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}
}
FileCrawler
is IO bound runnable task that gets launched on multiple threads which perform crawl(root)
IO functionality.
Java thread is internally mapped to native thread(equivalent to pthread_create()
). Each pthread is mapped to a different thread in the kernel, and the kernel is responsible for scheduling the threads.
So, each java thread is visible to OS. It runs on specific cpu core.
Assume java process is running on OS that follows 1:1 threading model.
A java thread performing IO on a cpu core,
Does producer thread waiting on IO triggers kernel to context switch out the java process and put the java process into a waiting state until the IO is ready to be processed? Not getting chance for other threads(CPU bound) of java process to consume CPU time slice.
回答1:
Java thread is internally mapped to native thread (equivalent to
pthread_create()
).
What Java threads map to is implementation-dependent.
Each pthread is mapped to a different thread in the kernel
This is just nonsense.
and the kernel is responsible for scheduling the threads.
Correct, if the Java threads are native threads.
So, each java thread is visible to OS.
Correct if ditto.
It runs on specific cpu core.
Not necessarily.
Assume java process is running on OS that follows 1:1 threading model.
A java thread performing IO on a cpu core,
Does producer thread waiting on IO triggers kernel to context switch out the java process and put the java process into a waiting state until the IO is ready to be processed?
No. The process remains runnable if it has other runnable threads.
Not getting chance for other threads(CPU bound) of java process to consume CPU time slice.
No, the other threads can still run if they are runnable.
This is all very confused and rests on a number of incorrect or implementation-specific assumptions.
来源:https://stackoverflow.com/questions/46902158/java-io-bound-thread-11-threading-model