黑马程序员技术交流社区
标题:
在处理多线程是为什么要加上处理异常
[打印本页]
作者:
nestor
时间:
2014-4-2 13:34
标题:
在处理多线程是为什么要加上处理异常
本帖最后由 nestor 于 2014-4-2 14:54 编辑
class Res{
private String name;
private String sex;
private boolean flag = false;
public synchronized void set(String name,String sex){
if(flag)
try{this.wait();}catch(Exception e){}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
public synchronized void out(){
if(!flag)
try{this.wait();}catch(Exception e){}
System.out.println(name+"##"+sex);
flag = false;
this.notify();
}
}
class Input implements Runnable{
private Res r;
Input(Res r){
this.r = r;
}
public void run(){
int x = 0;
while(true){
if(x==0)
r.set("li", "man");
else
r.set("wang", "woman");
x = (x+1)%2;
}
}
}
class Output implements Runnable{
private Res r;
Output(Res r){
this.r = r;
}
public void run() {
while(true){
r.out();
}
}
}
class InputOut{
public static void main(String[] args){
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
复制代码
if(flag) try{this.wait();}catch(Exception e){}
为什么
第8行和第16行需要处理异常?
作者:
osully
时间:
2014-4-2 13:36
这个方法是抛出异常的 ,所以你在调用一个抛出异常的方法时 要么try catch 要么调用的函数上继续抛出异常
public final void wait() throws InterruptedException
作者:
Crystal静新
时间:
2014-4-2 14:23
这是要抛异常的,这个你如果用IDE工具开发,一般都会有提示你的,要你就到JDK文档上看看,这个方法要不要抛异常,需要抛异常就按它的要求做处理,至于两哪种方式,楼上的已经讲了,我就不再细说了。
作者:
Peach2014
时间:
2014-4-2 15:50
本帖最后由 Peach2014 于 2014-4-2 15:52 编辑
public final void wait() throws
InterruptedException
这个是wait()方法的概要,因为wait()方法抛出异常,在使用的就需要处理这个异常,对于异常的处理有两种方法:1,继续抛出;2,直接处理(try-catch)
这里使用的是第二种方法。
作者:
孔丽阁
时间:
2014-4-2 17:34
基本上所有的流都是带有异常的,因为可能出现的错太多了。所有源码上面本身就要求要处理这个异常。
作者:
leon_hm
时间:
2014-4-2 18:36
public
interface Runnable {
public abstract void run();
}
以上是Runnable的源代码
实现Runnable接口的时候,必须要覆盖run()方法。
如果不在run()里面用try catch处理异常,则只能写成如下。
而如下代码不是Runnable接口中run()方法的重写,编译都没法通过的
public void run() throws Exception
{
};
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2