黑马程序员技术交流社区
标题:
多线程 难点 锁和等待唤醒机制
[打印本页]
作者:
792241113
时间:
2016-10-13 02:27
标题:
多线程 难点 锁和等待唤醒机制
public class Test1 {
public static void main(String[] args) {
Student s = new Student();
Get G = new Get(s);
Set S = new Set(s);
Thread t1 = new Thread(G);
Thread t2 = new Thread(S);
t2.start();
t1.start();
}
}
public class Student {
private String name;
private int age;
private boolean flag;
public synchronized void set (String name ,int age){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name=name;
this.age=age;
this.flag=true;
this.notify();
}
public synchronized void get(){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(this.name+this.age+"个");
this.flag=false;
this.notify();
}
}
public class Set implements Runnable {
Student s;
public Set(Student s) {
this.s = s;
}
@Override
public void run() {
int i = 0;
while (true) {
if (i%2==0){
s.set("生产包子中,没有了:",0);
}else{
s.set("卖包子咯 还有:", 10);
}
i++;
}
}
}
public class Get implements Runnable {
private Student s;
public Get(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
s.get();
}
}
}
作者:
792241113
时间:
2016-10-13 02:28
这个是 距举例说明的 比较难理解的就是 这个上锁 以及 这个 等待唤醒机制 为了追求两个线程相互唤醒 相互等等待
作者:
792241113
时间:
2016-10-13 02:29
如果 有什么 不懂的 可以留言给我 我会帮你解答 我感觉 也就是这四个布尔 比较难理解 别绕进去 如果绕进去 你就半小时出不来
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2