有两种创建线程的方法:一是实现Runnable接口,然后将它传递给Thread的构造函数,创建一个Thread对象;二是直接继承Thread类。
当我们在Java程序中新建一个线程时,它的状态是New。当我们调用线程的start()方法时,状态被改变为Runnable。线程调度器会为Runnable线程池中的线程分配CPU时间并且讲它们的状态改变为Running。其他的线程状态还有Waiting,Blocked 和Dead。
public class SimpleWN {
final static Object object=new Object();
public static class T1 extends Thread{
public void run(){
synchronized(object){
System.out.println(new Date()+":T1 start");
try {
System.out.println(new Date()+":T1 wait for Object");
object.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(new Date()+":T1 end");
}
}
}
public static class T2 extends Thread{
public void run(){
synchronized(object){
System.out.println(new Date()+":T2 start,notify one thread");
object.notify();
System.out.println(new Date()+":T2 end");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Thread t1= new T1();
Thread t2= new T2();
t1.start();//
t2.start();//wait 会释放对象锁 而sleep不会释放任何资源
}
}