小编Ser*_*esh的帖子

为什么我必须在try/catch语句中包装每个Thread.sleep()调用?

我正在尝试用Java编写我的第一个多线程程序.我无法理解为什么我们需要围绕for循环进行此异常处理.当我在没有try/catch子句的情况下编译时,它会产生InterruptedException.(这是消息:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Unhandled exception type InterruptedException
Run Code Online (Sandbox Code Playgroud)

)

但是当使用try/catch运行时,catch块中的sysout永远不会显示 - 这意味着没有捕获到这样的异常!

public class SecondThread implements Runnable{
    Thread t;

    SecondThread(){
        t = new Thread(this, "Thread 2");
        t.start();
    }

    public void run(){
        try{
            for(int i=5 ; i>0 ; i--){
                System.out.println("thread 2: " + i);
                Thread.sleep(1000);
            }
        }
        catch(InterruptedException e){
            System.out.println("thread 2 interrupted");
        }
    }
}


public class MainThread{

    public static void main(String[] args){
        new SecondThread();

        try{
            for(int i=5 ; i>0 ; i--){
                System.out.println("main thread: …
Run Code Online (Sandbox Code Playgroud)

java interrupted-exception interruption

2
推荐指数
1
解决办法
9946
查看次数

如果 char 是 2 个字节,为什么 read() 一次读取一个字节?

如果我们的文本文件中有一个 unicode 字符,它不是必须是 2 个字节的数据吗?但是该read()方法一次读取一个字节作为int. 所以如果我们有一个FileInputStream对象fin并且我们调用了int x = fin.read()一次,System.out.println(x)如果只读取了一个字节,我们如何获得完整的字符?(fin.read()不在while循环或任何东西中,它只被调用一次)

java io

1
推荐指数
1
解决办法
1609
查看次数

标签 统计

java ×2

interrupted-exception ×1

interruption ×1

io ×1