黑马程序员技术交流社区
标题:
郁闷
[打印本页]
作者:
kenfine
时间:
2015-1-14 23:00
标题:
郁闷
今天做了一道程序,主要是线程的之间的同步与通信,之前做过一样的,今天看了一次视频,然后模仿着做,但还是有一点点小细节耽搁了我近一小时,很郁闷自己的逻辑抽象思维那么差。上代码:
class Person{
private String name;
private int age;
private boolean b=true;
public synchronized void set(String name,int age){
if(b)
try {
this.wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
this.name=name;
this.age=age;
b=true;
this.notify();
}
public synchronized void get(){
if(!b){
try {
this.wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
System.out.println("姓名"+this.name+".....年龄"+this.age);
b=false;
this.notify();
}
}
class Input implements Runnable{
private Person p;
private int x = 0;
public Input(Person p){
this.p=p;
}
@Override
public void run() {
while(true){
if(x==0)
p.set("张三", 20);
else
p.set("李四", 30);
x=(x+1)%2;
}
}
}
class Output implements Runnable{
private Person p;
public Output(Person p){
this.p=p;
}
@Override
public void run() {
while(true){
p.get();
}
}
}
public class Syn
{
public static void main(String arg[])
{
Person p=new Person();
new Thread(new Input(p)).start();
new Thread(new Output(p)).start();
}
}
复制代码
其中,18-21,32-34不能用else扩起来,体会了线程是在this.wait();挂起,然后被唤醒是线程从this.wait();后面的语句继续执行,根本不存在if..else逻辑...
作者:
466273082
时间:
2015-1-14 23:56
还没有学习到,先暂时过来看看
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2