编写一个控制线程生命周期的程序,按以下步骤进行:
       1)创建线程对象,设置线程名称
       2)启动线程
   3) 调用sleep方法使线程进入休眠状态
   4)线程从sleep方法中恢复为运行状态后使用wait挂起线程
       5)使用主线程唤醒挂起的线程
       6)线程结束
    要求上述每个环节执行前后执行完毕后均向控制台输出消息,表示线程状态改变下面的我写的错误程序  大家帮我看看
 
 public class ThreadTest3 {
public static void main(String[] args){
A a=new A();
Thread threadone=new Thread(a);
threadone.start(); threadone.notifyAll();
System.out.println("主线程结束");
}}
class A implements Runnable{
public void run(){
for (int i=0;i<10;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread"+i);
}
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

解决方案 »

  1.   

    大概在楼主的基础上修改了一下
    public class ThreadTest3 {
    public static void main(String[] args){
    try {
    A a=new A();
    Thread threadone=new Thread(a);
    threadone.start();
    Thread.sleep(); //主线程休眠,让线程先执行
    synchronized(A.class) { //使用wait,notifyAll要用同步
    A.class.notifyAll();
    }
    System.out.println("主线程结束");
    }
    } catch (Throwable e) {
        e.printStackTrace();
    }}
    class A implements Runnable{
    public void run(){
    synchronized(A.class){ //要用同步
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println(Thread.currentThread()); try {
    A.class.wait();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }
    }