java 线程相关知识

来源:互联网 发布:淘宝美工学习网站 编辑:程序博客网 时间:2024/05/21 08:54
Java是通过Object类的wait、notify、notifyAll这几个方法来实现线程间的通信的,又因为所有的类都是从Object继承的,所以任何类都可以直接使用这些方法。


wait:告诉当前线程放弃监视器并进入睡眠状态,直到其它线程进入同一监视器并调用notify为止。
notify:唤醒同一对象监视器中调用wait的第一个线程。类似排队买票,一个人买完之后,后面的人可以继续买。
notifyAll:唤醒同一对象监视器中调用wait的所有线程,具有最高优先级的线程
首先被唤醒并执行。


多线程中,suspend方法、resume方法和stop方法不推荐使用。


public class ThreadCommunation {
public static void main(String args[]) {

Person person = new Person();

new Thread(new Producer(person)).start();
new Thread(new Consumer(person)).start();
}
}


class Producer implements Runnable {
private Person mPerson;

public Producer(Person persion) {
mPerson = persion;
}


public void run() {

int i = 0;

while(true) {
if (i == 0) {
mPerson.set("男", "张三");
} else {
mPerson.set("女", "李四");
}
i = (i + 1) % 2;
}

}

}


class Consumer implements Runnable {
private Person mPerson;
public Consumer(Person persion) {
mPerson = persion;
}


public void run() {
// TODO Auto-generated method stub
while(true) {
mPerson.get();
}
}

}


class Person {
private String sex = "男";
private String name = "张三";

boolean bFull = false;

public synchronized void get() {
if(!bFull) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

System.out.println(this.name +"----->"+this.sex);
bFull = false;
notify();

}
public synchronized void  set(String sex, String name) {

if(bFull) {

try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.name = name;
}

try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

this.sex = sex;
bFull = true;
notify();
}

}