线程间通信-示例

package com.huaWei.threadCommunication;


/**
 * 线程间通信资源类 
 * 线程间通信:多个线程在处理同一资源,但是任务却不同。
 * 
 * @author 华伟科技
 * 
 */
public class Resource {


private String name;
private String sex;
private boolean flag = false;


// 同步的好处:解决了线程的安全问题。
// 同步的弊端:相对降低了效率,因为同步外的线程都会判断同步锁。
// 同步的前提:必须有多个线程并使用同一个锁。
// 等待/唤醒机制,涉及的方法:
// (1)wait:让线程处于等待状态,被wait的线程会被存储在线程池中。
// (2)notify:唤醒线程池中一个线程(任意)。
// (3)notifyAll:唤醒线程池中所有的线程。
// 这些方法都必须定义在同步中,因为这些方法是用于操作线程状态的方法,必须要明确到底操作的是哪个锁上的线程。
// 为什么操作线程的方法wait、notify、notifyAll定义在Object类中?
// (1)因为这些方法是监视器的方法,监视器其实就是锁。
// (2)锁可以是任意的对象,任意的对象调用的方式一定定义在Object类中。

public synchronized void set(String name, String sex) {
if (flag)
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}


public synchronized void out() {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(name + "......." + sex);
flag = false;
this.notify();
}

}


package com.huaWei.threadCommunication;


/**
 * 输入线程
 * 
 * @author 华伟科技
 * 
 */
public class Input implements Runnable {

private Resource resource;


public Input(Resource resource) {
this.resource = resource;
}


@Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
while (true) {
if (i == 0) {
resource.set("mike", "man");
} else {
resource.set("丽丽", "女女女女女女女女女女女");
}
i = (i + 1) % 2;
}
}


}


package com.huaWei.threadCommunication;


/**
 * 输出线程
 * 
 * @author 华伟科技
 * 
 */
public class Output implements Runnable {


private Resource resource;


public Output(Resource resource) {
this.resource = resource;
}


@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
resource.out();
}
}


}


package com.huaWei.threadCommunication;


/**
 * 线程间通信测试类
 * 
 * @author 华伟科技
 * 
 */
public class ThreadCommunicationMain {


public static void main(String[] args) {


threadCommunication();


}


public static void threadCommunication() {
// 创建资源
Resource resource = new Resource();
// 创建任务
Input input = new Input(resource);
Output output = new Output(resource);
// 创建线程,执行路径
Thread thread1 = new Thread(input);
Thread thread2 = new Thread(output);


// 开启线程
thread1.start();
thread2.start();
}


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值