java线程之线程通信

前面提到多线程操作会有一个资源共享问题。

日常生活中,对于一个超市,有供货商往超市运货,有消费者从超市取货,供货商和消费者都与超市

建立了某种连接,超市就相当于公共资源,而他们的这种行为放到线程上说就是----线程通信。

建立线程通信自然少不了公共资源类、至少两个操作线程、测试类。

1.公共资源类

 1 public class Share {
 2     String name;
 3     String sex;
 4     //线程A的任务,提供数据(同步方法)
 5     public synchronized void product(String name,String sex) {
 6         this.name = name;
 7         this.sex = sex;
 8     }
 9     //线程B的任务,提取(显示)数据(同步方法)
10     public synchronized void show() {
11         System.out.println("姓名:"+this.name+";性别:"+this.sex );
12     }
13 }

因为供货商和消费者都会与超市建立连接,那么超市自然要知道他们各自的目的。

所以公共资源类中会定义各线程的操作方法(任务)。

2.线程A/B

 1 public class Producter implements Runnable {
 2     Share share = null;
 3     // 构造方法为此线程和公共资源对象建立连接
 4     public Producter(Share share) {
 5         this.share = share;
 6     }
 7     @Override
 8     public void run() {
 9         // run方法定义了线程工作时的具体操作
10         share.product("Tom", "男");
11     }
12 }
13 
14 
15 
16 
17 public class Customer implements Runnable {
18     Share share = null;
19     // 构造方法为此线程和公共资源对象建立连接
20     public Customer(Share share) {
21         this.share = share;
22     }
23     @Override
24     public void run() {
25         // run方法定义了线程工作时的具体操作
26         share.show();
27     }
28 }

由于线程A/B都是对公共资源对象的操作,那么就必须在线程内部引入公共资源对象,为后面的线程操作(run方法)提供对象。

3.测试类(开始工作)

 1 public class Test {
 2     public static void main(String[] args) {
 3         //新建一个公共资源类对象share
 4         Share share = new Share();
 5         //创建线程A/B,并为其引入公共资源对象(构造器实现对象引入)
 6         Producter product = new Producter(share);
 7         Customer   customer = new Customer(share);
 8         //开启线程,二位开始上班
 9         new Thread(product, "A").start();
10         new Thread(custmer, "B").start();
11     }
12 }

不难看出,控制台会打印出A线程传入的数据(姓名:Tom;性别:男)

原文地址:https://www.cnblogs.com/eco-just/p/7770436.html