1 package 多线程;
 2 class Producer implements Runnable{
 3     private Data data;
 4     public Producer(Data data){
 5         this.data=data;
 6     }
 7     @Override
 8     public synchronized void run() {
 9         for(int i=0;i<50;i++){
10             if(i%2==0){
11                 this.data.setTitle("饼干");
12                 try {
13                     Thread.sleep(100);
14                 } catch (InterruptedException e) {
15                     e.printStackTrace();
16                 }
17                 this.data.setValue("麦香饼干");
18             }else{
19                 this.data.setTitle("饮料");
20                 try {
21                     Thread.sleep(100);
22                 } catch (InterruptedException e) {
23                     e.printStackTrace();
24                 }
25                 this.data.setValue("果汁好喝");
26             }
27         }
28     }
29 }
30 class Consumer implements Runnable{
31     private Data data;
32     public Consumer(Data data){
33         this.data=data;
34     }
35     @Override
36     public synchronized void run() {
37         for(int i=0;i<50;i++){
38             try {
39                 Thread.sleep(100);
40             } catch (InterruptedException e) {
41                 e.printStackTrace();
42             }
43             System.out.println("消费:"+this.data.getTitle()+"->"+this.data.getValue());
44         }
45     }
46 }
47 class Data{
48     private String title;
49     private String value;
50     public void setTitle(String title) {
51         this.title = title;
52     }
53     public String getTitle() {
54         return title;
55     }
56     public void setValue(String value) {
57         this.value = value;
58     }
59     public String getValue() {
60         return value;
61     }
62 }
63 public class TestProducerConsumer {
64     public static void main(String[] args) {
65         Data data=new Data();
66         new Thread(new Producer(data)).start();
67         new Thread(new Consumer(data)).start();
68     }
69 }
数据错乱

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-22
  • 2022-12-23
  • 2021-12-29
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-09
  • 2022-03-09
  • 2021-07-01
  • 2021-06-22
  • 2021-10-15
  • 2021-07-10
相关资源
相似解决方案