java语言中的线程的通讯问题

作者:白雪 | 创建时间: 2023-06-21
这是学习java语言的基础篇,大家只可参考阅读...
java语言中的线程的通讯问题

操作方法

首先要明确,线程间的通讯问题,就是让多个线程操作同一个资源

其次  通过代码来解决这些问题 首先: 新建一个共享资源 class Res { String name; String sex; }

其次建立两个线程,来操作这个资源 class Input implements Runnable { Res  r; Input(Res r) { this.r=r; } public void run() { boolean b =true; while(true) { if(b) { r.name="lishi"; r.sex="man"; b = false; } else { r.name="李四"; r.sex="男"; b = true; } } } } } class Output implements Runnable { Res  r; Output(Res r) { this.r=r; } public void run() { while(true) { System.out.println(r.name+"  "+r.sex); } } } 然后新建一个测试类: public class Demo { public static void main(String[] args) { Res  r = new Res(); Input in = new Input(r); Output out = new Output(r); Thread t = new Thread(in ); Thread tl = new Thread(out); t.start(); tl.start(); } } 我们会发现些小程序在运行过程中会出现安全问题,那么要解决线程间的安全问题,就需要用到同步代码块的知识 我们要以将上面的代码改写:

class Res{ String name; String sex;  }class Input implements Runnable{ Res  r; Input(Res r) { this.r=r; } public void run() { boolean b =true; while(true) { synchronized(r) { if(b) { r.name="lishi"; r.sex="man"; b = false; } else { r.name="李四"; r.sex="男"; b = true; } } } } }class Output implements Runnable{ Res  r; Output(Res r)    {       this.r=r;     } public void run() { while(true) { synchronized(r) { System.out.println(r.name+"  "+r.sex); } } } } 这样的话就解决了线程间的安全问题了 输出正确的结果应该为

生产者与 消费者问题

public class StringDemo { public static void main(String[] args) { Resourced r = new Resourced(); new Thread(new Producerd(r)).start();//1 new Thread(new Producerd(r)).start();//2 new Thread(new Consumerd(r)).start();//3 new Thread(new Consumerd(r)).start();//4 } } /* * 生产一个,消费一个*/ class Resourced { private String name; private int count  = 1; private boolean flag = false; public synchronized void set(String name) { while(flag) try{wait();}catch(Exception e){} this.name = name+"  "+count++; System.out.println(Thread.currentThread().getName()+"生产者,,,," + this.name); flag = true; this.notifyAll(); } public synchronized void out() { while(!flag) try{wait();}catch(Exception e){} System.out.println(Thread.currentThread().getName()+"消费者    " + this.name); flag = false; this.notifyAll(); } } class Producerd implements Runnable { private Resourced res ; Producerd(Resourced res) { this.res = res; } public void run() { while(true) { res.set("商品"); } } } class Consumerd implements Runnable { private Resourced res; Consumerd(Resourced res) { this.res = res; } public void run() { while(true) { res.out(); } } }

温馨提示

请仔细参读
点击展开全文

更多推荐