多线程之间的通讯
多线程之间如何实现通讯
什么是多线程之间通讯?
多线程之间通讯,其实就是多个线程在操作同一个资源,但是操作的动作不同。
画图演示
多线程之间通讯需求
需求:第一个线程写入(input)用户,另一个线程取读取(out)用户.实现读一个,写一个操作。
代码实现基本实现
下面我们看个例子 生产者 消费者
package com.toov5.thread;
//共享对象
class Res{
public String sex;
public String name;
}
class inputThread extends Thread{
public Res res;
public inputThread(Res res) {
this.res=res;
}
@Override
public void run() {
int count=0;
while (true) {
if (count==0) {
res.name="lucy";
res.sex="girl";
}else {
res.name="Jack";
res.sex="boy";
}
count =(count+1)%2;
}
}
}
class readThread extends Thread{
public Res res;
public readThread(Res res) {
this.res=res;
}
@Override
public void run() {
while (true) {
System.out.println(res.name+","+res.sex);
}
}
}
public class ConmunicatThreadTest {
//开启两个线程 下面的线程 主线程 还有这俩用户线程 cpu随机的
public static void main(String[] args) {
Res res = new Res();
inputThread inputThread = new inputThread(res);
readThread readThread = new readThread(res);
inputThread.start();
readThread.start();
}
}
结果
有问题的了
需要解决线程问题,每个线程的本地内存没有及时刷新到主内存中去
好合理使用synchronize关键字哟
package com.toov5.thread;
//共享对象
class Res{
public String sex;
public String name;
}
class inputThread extends Thread{
public Res res;
public inputThread(Res res) {
this.res=res;
}
@Override
public void run() {
int count=0;
while (true) {
synchronized (res) {
if (count==0) {
res.name="lucy";
res.sex="girl";
}else {
res.name="Jack";
res.sex="boy";
}
count =(count+1)%2;
}
}
}
}
class readThread extends Thread{
public Res res;
public readThread(Res res) {
this.res=res;
}
@Override
public void run() {
while (true) {
synchronized (res) {
System.out.println(res.name+","+res.sex);
}
}
}
}
public class ConmunicatThreadTest {
//开启两个线程 下面的线程 主线程 还有这俩用户线程 cpu随机的
public static void main(String[] args) {
Res res = new Res();
inputThread inputThread = new inputThread(res);
readThread readThread = new readThread(res);
inputThread.start();
readThread.start();
}
}
读的时候不能写 写的时候不能读 上锁啦~~
结果
这下OK了,生产者消费者 都加锁了 而且是同一把锁
在写的时候 读的线程不能进进行读
在读的时候,写的线程不能进行写