Discuss / Java / 例子疑问

例子疑问

Topic source

不惑之年

#1 Created at ... [Delete] [Delete and Lock User]
void register() {
    config = readConfigFile("./config.json"); // #1
    if (config.useFullName) {
        name = req.firstName + " " + req.lastName;
    }
    insertInto(db, name); // #2
    if (config.cache) {
        redis.set(key, name); // #3
    }
}

想问问廖老师,这里的 #2 #3 需要用到 #1 读取到的值 config 之后才能进行后续操作,看起来只有 #2 #3不会相互有依赖,所以只有 2,3 才能用虚拟线程对吧

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

vthread和依赖没有任何关系。

vthread只跟io有关,进入io时自动挂起,io结束后继续运行,你用for循环读100个文件就会导致它挂起-运行100次:

for (int i=0; i<100; i++) {
    readFile("test-" + i + ".txt");
}

不惑之年

#3 Created at ... [Delete] [Delete and Lock User]

谢谢老师,看了你这个例子,懂了


  • 1

Reply