class MyThread extends Thread{
String sa;
public MyThread(String sa){
this.sa=sa;
}
public void run(){
synchronized(sa){
while(!sa.equals("done")){
try{
sa.wait();
}catch(InterruptedException e){
System.out.println("haha");
}
}
}
System.out.println(sa);
}
}public class ThreadTest {
private static String sa=new String("not done");
public static void main(String[] args){
MyThread mt=new MyThread(sa);
mt.start();
synchronized(sa){
try{
sa=new String("done");
sa.notify();
}catch(Exception e1){
e1.printStackTrace();//错误在这里抛出
}
}
}
}
问题是:错误虽然抛出,但并不是我想要的InterruptedException,请问为什么会抛出异常?
try{
sa.wait();
}使占用sa的对象锁,
在main函数中
synchronized(sa){
try{
sa=new String("done");
sa.notify();
}肯定会跑出异常,sa=new String("done");重新申请了一个对象你调用sa.notify();此时sa并没有被wait,主要是sa属于不同对象!下面是我改的代码:可以正常执行!
package mypackae;
class MyThread extends Thread{
String sa;
public MyThread(String sa){
this.sa=sa;
}
public void run(){
synchronized(sa){
while(!sa.equals("done")){
try{
sa.wait();
}catch(InterruptedException e){
System.out.println("haha");
}
}
}
System.out.println(sa);
}
public void set(String str)
{
this.sa=str;
}
}
public class Main
{ public static void main(String[] args){
String sa=new String("not done");
MyThread mt=new MyThread(sa);
mt.start();
synchronized(sa){
try{
sa.notify();
mt.set("done");
}catch(Exception e1){
System.out.println(sa);
e1.printStackTrace();
}
}
}
}
{
String sa; public MyThread(String sa)
{
this.sa = sa;
} public void run()
{
synchronized (sa)
{
while (!sa.equals("done"))
{
try
{
sa.wait();
} catch (InterruptedException e)
{
System.out.println("haha");
}
}
}
System.out.println(sa);
} public void set(String str)
{
this.sa = str;
}
}public class Main
{ public static void main(String[] args)
{
String sa = new String("not done");
MyThread mt = new MyThread(sa);
mt.start();
for (int i = 1; i < 10; i--)
{ }
synchronized (mt)
{
try
{
mt.interrupt();
mt.set("done"); } catch (Exception e1)
{
System.out.println(sa);
e1.printStackTrace();
}
} }}
这个代码会产生InterruptedException 异常!因为对一个进入中断状态的线程调用中断会产生该异常!