e094. determining when a thread has finished.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 36 行

TXT
36
字号
This example demonstrates a few ways to determine whether or not a thread has returned from its run() method. 
    // Create and start a thread
    Thread thread = new MyThread();
    thread.start();
    
    // Check if the thread has finished in a non-blocking way
    if (thread.isAlive()) {
        // Thread has not finished
    } else {
        // Finished
    }
    
    // Wait for the thread to finish but don't wait longer than a
    // specified time
    long delayMillis = 5000; // 5 seconds
    try {
        thread.join(delayMillis);
    
        if (thread.isAlive()) {
            // Timeout occurred; thread has not finished
        } else {
            // Finished
        }
    } catch (InterruptedException e) {
        // Thread was interrupted
    }
    
    // Wait indefinitely for the thread to finish
    try {
        thread.join();
        // Finished
    } catch (InterruptedException e) {
        // Thread was interrupted
    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?