使用多线程实现生产者和消费者 public class ThreadTest extends Thread { class Res{ private String username; private int age; } class input extends Thread{ Res res; public input(Res res) { this.res = res; } @Override public void run() { int count=0; while(true){ //千万不要写成synchronized (this),这里的this指的是当前类对象即input对象 //synchronized是指对同一把锁进行控制;input和output显然不是同一把锁,故使用synchronized (this)没有对锁控制 synchronized (res){ if (count ==0){ res.username="lili"; res.age=15; }else { res.username = "dandan"; res.age= 18; } } count=(count+1)%2; } } } class output extends Thread{ Res res; public output(Res res) { this.res = res; } @Override public void run() { while(true){ //千万不要写成synchronized (this),这里的this指的是当前类对象即output对象 synchronized (res){ System.out.println(res.username+','+res.age); } } } } public static void main(String[] args) { //main方法是一个static方法,class Res是一个非静态的内部类,只能被该类的非静态方法访问。否则会报错。 //new Res(); new ThreadTest().start(); } public void start(){ //创建共享对象 Res res=new Res(); //写的线程 new input(res).start(); //读的线程 new output(res).start(); } }
2021-03-29
最新推荐文章于 2024-10-06 20:16:20 发布
该博客展示了如何在Java中使用多线程实现经典的生产者消费者问题。通过创建`input`线程作为生产者,`output`线程作为消费者,利用共享资源类`Res`并使用`synchronized`关键字确保线程安全。生产者线程交替设置用户名和年龄,而消费者线程则不断打印这些信息。博客强调了避免在`synchronized`块中使用`this`关键字以防止锁错误。
摘要由CSDN通过智能技术生成