这是学习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();
}
}
}
注意事项请仔细参读经验内容仅供参考,如果您需解决具体问题(尤其法律、医学等领域),建议您详细咨询相关领域专业人士。作者声明:本教程系本人依照真实经历原创,未经许可,谢绝转载。
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
