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