加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

线程等待与唤醒案例

发布时间:2021-05-20 08:57:14 所属栏目:大数据 来源: https://blog.csdn.net/summoxj
导读:定义资源类: /* ?* 定义资源类,有2个成员变量 ?* name,sex ?* 同时有2个线程,对资源中的变量操作:1个对name,age赋值;2个对name,age做变量的输出打印 ?*/ public class Resource { ?? ?public String name; ?? ?public String sex; ?? ?public boolean
定义资源类:

/*
?* 定义资源类,有2个成员变量
?* name,sex
?* 同时有2个线程,对资源中的变量操作:1个对name,age赋值;2个对name,age做变量的输出打印
?*/
public class Resource {
?? ?public String name;
?? ?public String sex;
?? ?public boolean flag=false;

}


InputThread类实现Runnable:

/*
?* 输入的线程,对资源对象Resource中成员变量赋值
?* 一次赋值:张三,男;下一次赋值:李四,女
?*/
public class InputThread implements Runnable {
?? ?private Resource r;
?? ?
?? ?public InputThread(Resource r){
?? ??? ?this.r=r;
?? ?}
?? ?
?? ?public void run() {
?? ??? ?int i=0;
?? ??? ?while(true){
?? ??? ??? ?synchronized (r) {
?? ??? ??? ??? ?//标记是true,等待
?? ??? ??? ??? ?if(r.flag){
?? ??? ??? ??? ??? ?try{
?? ??? ??? ??? ??? ??? ?r.wait();
?? ??? ??? ??? ??? ?}catch(Exception ex){}
?? ??? ??? ??? ?}
?? ??? ??? ??? ?if(i%2==0){
?? ??? ??? ??? ??? ?r.name="张三";
?? ??? ??? ??? ??? ?r.sex="男";
?? ??? ??? ??? ?}else{
?? ??? ??? ??? ??? ?r.name="lisi";
?? ??? ??? ??? ??? ?r.sex="女";
?? ??? ??? ??? ?}
?? ??? ??? ??? ?//将对方线程唤醒,标记改为true
?? ??? ??? ??? ?r.flag=true;
?? ??? ??? ??? ?r.notify();
?? ??? ??? ?}
?? ??? ??? ?i++;
?? ??? ?}
?? ?}

}


OutputThread类实现Runnable:

/*
?* 输出线程,对资源对象Resource中的成员变量,输出值
?*/
public class OutputThread implements Runnable {
?? ?private Resource r;
?? ?
?? ?public OutputThread(Resource r){
?? ??? ?this.r=r;
?? ?}
?? ?
?? ?public void run() {
?? ??? ?while(true){
?? ??? ??? ?synchronized (r) {
?? ??? ??? ??? ?//判断标记,是false,等待
?? ??? ??? ??? ?if(!r.flag){
?? ??? ??? ??? ??? ?try {
?? ??? ??? ??? ??? ??? ?r.wait();
?? ??? ??? ??? ??? ?} catch (Exception ex) {}
?? ??? ??? ??? ?}
?? ??? ??? ??? ?System.out.println(r.name+"..."+r.sex);
?? ??? ??? ??? ?//标记改为false,唤醒对方线程
?? ??? ??? ??? ?r.flag=false;
?? ??? ??? ??? ?r.notify();
?? ??? ??? ?}
?? ??? ?}
?? ?}

}


测试类:

/*
?* 开启输入线程和输出线程,实现赋值和打印值
?*/
public class ThreadDemo {
?? ?public static void main(String[] args) {
?? ??? ?Resource resource=new Resource();
?? ??? ?
?? ??? ?InputThread in=new InputThread(resource);
?? ??? ?OutputThread out=new OutputThread(resource);
?? ??? ?
?? ??? ?Thread tin=new Thread(in);
?? ??? ?Thread tout=new Thread(out);
?? ??? ?
?? ??? ?tin.start();
?? ??? ?tout.start();
?? ?}
}




(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读