java线层的启动与停止
2015-08-09 20:06
726 查看
class Do8 { public static void main(String[] args) { Resource r =new Resource(); 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 Resource { String name; String sex; boolean flag=false; } //输入 class Input implements Runnable { Resource r; Input(Resource r) { this.r=r; } public void run() { int x=0; while(true) { synchronized(r) { if(r.flag) { try{r.wait();}catch(Exception e){}//为真的时候,当前线层停止 } if(x==0) { r.name="往里"; r.sex="男"; } else { r.name="xiaoli"; r.sex="wumen"; } r.flag=true; r.notify();//启动任意的停止的线层 } x=(x+1)%2; } } } //输出 class Output implements Runnable { Resource r; Output(Resource r) { this.r=r; } public void run() { while(true) { synchronized(r) { if(!r.flag) { try{r.wait();}catch(Exception e){}//不为真的时候,当前线层停止 } try{Thread.sleep(100);}catch(Exception e){} System.out.println(r.name+"..."+r.sex); r.flag=false; r.notify();//启动任意的停止的线层 } } } }
练习
class Do9 { public static void main(String[] args) { Resource r=new Resource(); Shengchan sc=new Shengchan(r); Xiaoshou xs=new Xiaoshou(r); Thread th1=new Thread(sc); Thread th2=new Thread(xs); th1.start(); th2.start(); } } class Resource { private String name; private int count=1; private boolean flag=false; public synchronized void set(String name) { if(flag) try{this.wait();}catch(InterruptedException e){} this.name=name+count; count++; System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name); flag=true; notify(); } public synchronized void out() { if(!flag) try{this.wait();}catch(InterruptedException e){} System.out.println(Thread.currentThread().getName()+"..消费者........"+this.name); flag=false; notify(); } } class Shengchan implements Runnable { private Resource r; Shengchan(Resource r) { this.r=r; } public void run() { while(true) { try{Thread.sleep(150);}catch(InterruptedException e){} r.set("烤鸭"); } } } class Xiaoshou implements Runnable { private Resource r; Xiaoshou(Resource r) { this.r=r; } public void run() { while(true) { try{Thread.sleep(150);}catch(InterruptedException e){} r.out(); } } }
相关文章推荐
- Java实现算法之--选择排序
- Java基础学习总结---------异常Exception(2)
- Java产生随机数
- 栈的链表实现(JAVA)
- java面向接口编程
- Java程序设计求出岁数
- 如何清楚描述spring
- 关于 java 实现 语音朗读
- 通过网页访问SQL数据库,提示java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriver
- spring的@Transactional注解详细用法
- Java字符串题目--删除给定字符串中出现次数最少的字符
- 一致性哈希算法与Java实现
- 【Java多线程】之十四:Java FutureTask Example Program
- 智渔课堂官方免费教程三:Java基础之注释 关键字 标识符
- I学霸官方免费教程三:Java基础之注释 关键字 标识符
- java项目转换成javaWeb项目
- Struts2 入门实例
- 华为上机 最小长方形 java
- Java注解之分类
- 【Java多线程】之十三:Java Callable Future Example