执行结果应该为:
Waiting for first thread to finish...
First thread starts running.
Second thread starts running.
Second thread suspends itself.
First thread finishes running.
It's a long wait!
Waking up second thread...
Waiting for second thread to finish...
Second thread runs again and finishes.
I'm ready to finish too.
根据执行的结果应该很容易知道执行的顺序了吧!
慢慢研究吧!
Waiting for first thread to finish...
First thread starts running.
Second thread starts running.
Second thread suspends itself.
First thread finishes running.
It's a long wait!
Waking up second thread...
Waiting for second thread to finish...
Second thread runs again and finishes.
I'm ready to finish too.
根据执行的结果应该很容易知道执行的顺序了吧!
慢慢研究吧!
还有对象Object的两个方法wait(),notify().
线程可以通过sleep()进入休眠状态,休眠的进程可以通过Thread.interrupt()被唤醒(会产生异常)。
线程也可以调用自身或其他对象的wait()方法进入休眠状态。休眠的进程可以通过Thread.interrupt()被唤醒(会产生异常),也可以通过object.notify()被唤醒。
这里面概念比较多。建议看Think in java中的相关描述。
package Myclass;
import java.io.*;
public class MethodTest
{
static PrintWriter out= new PrintWriter(System.out,true);
public static void main(String[] args)
{
FirstThread first=new FirstThread();//实例化FirstThread
SecondThread second=new SecondThread();//实例化SecondThread
first.start();//启动第一个线程
second.start();//启动第二个线程
try
{
out.println("Waiting for first thread to finish...");
first.join();//等待第一个线程结束
out.println("It's a long wait!");
out.println("Waking up second thread...");
synchronized(second){
second.notify();//通知第二个线程(因为第二个线程调用了wait方法)
}
out.println("Waiting for second thread to finish...");
second.join();//等待第二个线程结束
}
catch(InterruptedException e){}
out.println("I'm ready to finish too.");
}
}class FirstThread extends Thread
{
public void run()
{
try
{
MethodTest.out.println(" First thread starts running.");
sleep(10000);//休眠10000ms
MethodTest.out.println(" First thread finishes running.");
}
catch (InterruptedException e){}
}
}class SecondThread extends Thread
{
public synchronized void run()
{
try
{
MethodTest.out.println(" Second thread starts running.");
MethodTest.out.println(" Second thread suspends itself.");
wait();//等待其他对象唤醒
MethodTest.out.println(" Second thread runs again and finishes.");
}
catch (InterruptedException e)
{}
}
}