为避免死锁,就应该让线程在进入阻塞状态时尽量释放其锁定的资源,以为其他的线程提供运行的机会,Object类中定义了几个有用的方法:wait()、notify()、notifyAll()。
1.wait():被锁定的对象可以调用wait()方法,这将导致当前线程被阻塞并释放该对象的互斥锁,即解除了wait()方法当前对象的锁定状态,其他的线程就有 机会访问该 对象。
2.notify():唤醒调用wait()方法后被阻塞的线程。每次运行该方法只能唤醒一个线程。
3.notifyAll():唤醒所有调用wait()方法被阻塞的线程。
事例:
//资源类
class Res{
String name;
String sex;
booleanb;
}
class Inputimplements Runnable{
private Resr;
privateinti=0;
public Input(Res r){
this.r=r;
}
@Override
publicvoid run() {
//TODOAuto-generated method stub
while(true){
synchronized(r){
if(r.b)
try {
r.wait();
} catch (InterruptedException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
if(i==0){
r.name="张三";
r.sex="男";
}else{
r.name="李四";
r.sex="女";
}
r.b=true;
r.notify();
}
i=(i+1)%2;
}
}
}
class Outputimplements Runnable{
private Resr;
public Output(Res r){
this.r=r;
}
@Override
publicvoid run() {
//TODOAuto-generated method stub
while(true){
synchronized(r){
if(!r.b)
try {
r.wait();
} catch (InterruptedException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(r.name+"......"+r.sex);
r.b=false;
r.notify();
}
}
}
}
publicclass ThreadDemo1 {
/**
* @param args
*/
publicstaticvoid main(String[] args) {
//TODOAuto-generated method stub
Res re=new Res();
newThread(new Input(re)).start();
newThread(new Output(re)).start();
}
}
运行结果:
可以很清楚的看到,结果不会出现重复,错位等问题
定时器:Timer和TimerTask
¯java.util包中的Timer和TimerTask类也可实现多线程
¯Timer类实现的是类似闹钟的功能,也就是定时或者每隔一定时间间隔触发一次线程。
¯TimerTask类是一个抽象类,该类实现了Runnable接口,具备多线程的能力。
¯ 通过继承TimerTask类创建子类,使该子类获得多线程的能力,将需要多线程执行的代码书写在run方法内部,然后通过Timer类启动线程的执行。
importjava.util.Timer;
importjava.util.TimerTask;
class TimerTask1extends TimerTask {
publicvoid run() {
try{
for(int i = 0;i < 5;i++){
Thread.sleep(1000);
System.out.println("Run" + i);
}
}catch(Exception e){}
}
}
publicclass TestTimer {
publicstaticvoid main(String[] args) {
Timer t = new Timer();//定时器
TimerTask1 tt1 = new TimerTask1();
t.schedule(tt1, 0);//启动线程,tt1是需要启动的线程对象
try{
for(int i = 0;i < 5;i++){
Thread.sleep(1000);
System.out.println("Main:" + i);
}
}catch(Exception e){}
}
}
结果如下: