您的位置:首页 > 编程语言 > Java开发

Java-多线程的应用

2013-07-23 09:29 288 查看
class Info //主信息类

{

private String name="Aaron";

private String content="Ghost";

private boolean flag=false; //设置标志位

public void setname(String name)

{

this.name=name;

}

public String getname()

{

return this.name;

}

public void setcontent(String content)

{

this.content=content;

}

public String getcontent()

{

return this.content;

}

public synchronized void set(String name,String content)

{

if(!flag)

{

try

{

super.wait();//等待消费者取出

}catch(InterruptedException e)

{

e.printStackTrace();

}

}

this.setname(name);

try{

Thread.sleep(300);

}catch(InterruptedException e)

{

e.printStackTrace();

}

this.setcontent(content);

flag=false;//重置标志位,表示可以取走

super.notify();//唤醒等待线程

}

public synchronized void get()

{

if(flag)

{

try

{

super.wait();

}catch(InterruptedException e)

{

e.printStackTrace();

}

}

try{

Thread.sleep(90);

}catch(InterruptedException e)

{

e.printStackTrace();

}

System.out.println("姓名:"+this.getname()+"内容:"+this.getcontent());

flag=true; //修改标志位,表示可以恢复生产

super.notify(); //唤醒等待线程

}

}

class producer implements Runnable

{

private Info info=null;

public producer(Info info)

{

this.info=info;

}

public void run() //run方法的覆写

{

boolean flag=false;

for(int i=0;i<20;i++)

{

if(flag)

{

this.info.set("Aaron", "Ghost");

flag=false;

}

else

{

this.info.set("husiyun", "goal");

flag=true;

}

}

}

}

class consumer implements Runnable

{

private Info info=null;

public consumer(Info info)

{

this.info=info;

}

public void run() //run方法的覆写

{

for(int i=0;i<20;i++)

{

try

{

Thread.sleep(100);

}catch(InterruptedException e)

{

e.printStackTrace();

}

this.info.get();

}

}

}

public class test70 {

public static void main(String args[])

{

Info i=new Info(); //先实例化

producer pro=new producer(i);

consumer con=new consumer(i);

new Thread(pro).start();

new Thread(con).start();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: