一、对wait和sleep的个人理解
wait表示等待的意思,当线程调用wait方法时,线程将会处于等待状态,如果想要再次执行调用过wait方法的线程需要将其唤醒,使其脱离等待状态
sleep表示休眠的意思,这种休眠是有时间限制的,休眠时间到了执行sleep方法的线程会继续执行下去
二、区别:
(1)wait()被定义在Object类中,它有函数的重载形式,可以有毫秒值,也可以没有
(2)sleep()被定义在Thread类中,并且是一个static方法,必须有毫秒值
(3)wait()释放cpu执行权,释放锁
(4)sleep()释放cpu执行权,不释放锁
(5)wait()必须写在同步代码块中,也就是说需要有锁的支持
(6)sleep()可以写在任意地方,但是具体让哪个线程休眠,取决于哪个线程在执行该代码
代码演示等待-唤醒机制:
//线程间通信-等待唤醒机制
package thread;
class Resource1
{
String name;
String gender;
boolean flag;
public String toString()
{
return name+"---"+gender;
}
}
class Input1 implements Runnable
{
Resource1 resource;
Input1(Resource1 resource)
{
this.resource=resource;
}
public void run()
{
int i=0;
while(true)
{
synchronized (resource)
{
if(!resource.flag)
{
try
{
resource.wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
if(i%2==0)
{
resource.name="mike";
resource.gender="mail";
}
else
{
resource.name="迈克";
resource.gender="男";
}
resource.flag=false;
resource.notify();
}
i++;
}
}
}
class Output1 implements Runnable
{
Resource1 resource;
Output1(Resource1 resource)
{
this.resource=resource;
}
public void run()
{
while(true)
{
synchronized(resource)
{
if(resource.flag)
{
try
{
resource.wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(resource);
resource.flag=true;
resource.notify();
}
}
}
}
public class ThreadDemo4
{
public static void main(String[] args)
{
Resource1 resource=new Resource1();
Input1 in=new Input1(resource);
Output1 out=new Output1(resource);
Thread inThread=new Thread(in);
Thread outThread=new Thread(out);
inThread.start();
outThread.start();
}
}