线程之间的通信
来源:互联网 发布:淘宝美即面膜牛奶白滑 编辑:程序博客网 时间:2024/05/16 09:25
package demo.one;
/**
*
* 线程之间的通信其实就是多线程同时操作同一个资源 只是操作的动作不同
* 线程间的优化
*
*/
public class ThreadSocketTest {
/**
* @param args
*/
public static void main(String[] args) {
Person p = new Person();
Input in = new Input(p);
Output out = new Output(p);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
/**
*
* 资源
*
*/
class Person {
private String name;
private String sex;
private boolean status = false;
public synchronized void set(String name, String sex) {
if (status) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
this.name = name;
this.sex = sex;
this.status = true;
notify();
}
public synchronized void out() {
if (!this.status) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(this.name + ".........." + this.sex);
this.status = false;
notify();
}
}
/**
*
* 读取资源
*
*/
class Input implements Runnable {
private Person p;
public Input(Person p) {
this.p = p;
}
public void run() {
int num = 0;
while (true) {
if (num == 0) {
p.set("jacky", "male");
} else {
p.set("mexican", "female");
}
num=(num+1)%2;
}
}
}
/**
*
* 写入资源
*
*/
class Output implements Runnable {
private Person p;
public Output(Person p) {
this.p = p;
}
public void run() {
while (true) {
p.out();
}
}
}
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- java线程之间的通信
- 多线程-线程之间的通信
- linux线程之间的通信
- 关于java中Timer类的一个简单实例
- BSD下Enter full pathname of shell or RETURN for /bin/sh 解决办法
- vim编辑总结
- 内存字节对齐
- 介绍使用SrvAny.exe将tracd封装成windows服务。
- 线程之间的通信
- 制作自定义背景Button按钮、自定义形状Button的全攻略
- libvirt connections
- 使用ffmpeg 和mencoder 转换的相关参数和注意事项。
- JAVA 时间方法汇总(持续更新)
- 物流管理信息化
- Frequently used code snippet
- 第二章
- 从 Java 代码逆向工程生成 UML 类图和序列图