javaseday13

来源:互联网 发布:大数据云计算概念股 编辑:程序博客网 时间:2024/06/14 01:46

线程间通讯:多个线程在处理同一资源 ,但是任务不同

x++%2能实现 0 1 的切换

等待 唤醒机制

涉及的方法:

1、wait();  让线程处于冻结状态,被wait的线程会被存储到线程池中

2、notify(); 唤醒线程池中一个线程(任意)

3、notifyAll();唤醒线程池中的所有线程

输入不能new 因为要输出同个对象 还要用引用 所以传参进  Reasource r; 同时使用构造函数 传入

public class TestOra {
public static void main(String[] args) {
//创建资源  比如货物
Reasource r = new Reasource();
//创建任务 比如货车
Input in = new Input(r);
Output out = new Output(r);
//创建线程 执行路径 比如道路
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}


class Input implements Runnable{
Reasource r ;


Input (Reasource r){
this.r= r;
}
public void run() {
int x=0;
while (true) {
synchronized(r) {//资源就是唯一锁

if(x==0) {
r.name = "mike";
r.sex = "nan";
}

else {
r.name="bob";
r.sex="w";
}

}
x = (x+1)%2;//切换 输入进行测试
}
}
}


class Output implements Runnable{
Reasource r ;
Output(Reasource r){
this.r=r;
}
public void run() {
while(true) {
synchronized(r) {
System.out.println(r.name+"..."+r.sex);
}
}
}
}


class Reasource{
String name;
String sex;

}


这些方法度必须定义在同步中 因为这些方法是用于操作线程状态的方法

必须要明确到底操作的是哪个锁上的线程

为什么操作线程的方法 wait notify notifyall 定义在object 类中

因为这些方法是监视器的方法 监视器其实就是锁 线程池(等待集)

锁可以是任意的对象 任意的对象调用的方式一定定义在object类中

间隔输入就加上标志 和 wait() notify() 的应用

if(r.flag) {
try {
r.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

r.flag=true;
r.notify();

public class TestOra {
public static void main(String[] args) {
//创建资源  比如货物
Reasource r = new Reasource();
//创建任务 比如货车
Input in = new Input(r);
Output out = new Output(r);
//创建线程 执行路径 比如道路
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}


class Input implements Runnable{
Reasource r ;


Input (Reasource r){
this.r= r;
}


public void run() {
int x = 0;
while (true) {


if (x == 0) {
r.set("laomao", "nan");

}


else {
r.set("bob", "w");
}


x = (x+1)%2;//切换 输入进行测试
}
}
}


class Output implements Runnable {
Reasource r;


Output(Reasource r) {
this.r = r;
}


public void run() {
r.out();


}
}




class Reasource{
private String name;
private String sex;
private boolean flag=false;
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();
}
}