总结:Java多线程中wait和sleep的区别

一、对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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值