多线程模式之-single Threaded Execution Pattern

很简单的一个多线程模式之一,多个资源使用者使用资源时,资源类封装同步的方法,简单的加锁而于,属于一个使用者在使用其它使用者简单的等候,等候逻辑代码并不需要写,由Java虚拟机管理代码如下:
  1. public class MainThread {
  2.     public static void main(String[] args) {
  3.         System.out.println("Testing Gate, hit CTRL + C to exit");
  4.         Gate gate = new Gate();
  5.         new UserThread(gate, "Alice""Alaska").start();
  6.         new UserThread(gate, "Bobby""Brazil").start();
  7.         new UserThread(gate, "Chris""Canada").start();
  8.     }
  9. }
  10. /**
  11.  * ShareResource 共享资源参于者
  12.  * pass()方法与toString()方法的修饰符synchronized 确保资源的独享
  13.  */
  14. class Gate {
  15.     /** 保存的字段*/
  16.     private int counter = 0;
  17.     public String name ;
  18.     public String address;
  19.     /**
  20.      * 线程安全方法
  21.      * @param name String
  22.      * @param address String
  23.      */
  24.     public synchronized void pass(String name, String address) {
  25.         //1 2 3 4 的操作组合为原子级别的操作
  26.         counter++;                 //1
  27.         this.name = name ;         //2
  28.         this.address = address;    //3
  29.         check();                   //4
  30.     }
  31.     /**
  32.      * 线程安全方法
  33.      * @return String
  34.      */
  35.     public synchronized String toString() {
  36.         return "No" + counter + ":" + name + "," + address;
  37.     }
  38.     public void check() {
  39.         if (name.charAt(0) != address.charAt(0)) {
  40.             System.out.println("*****Broken*****" + toString());
  41.         }
  42.     }
  43. }
  44. /**
  45.  * UseResource 资源使用者
  46.  */
  47. class UserThread extends Thread{
  48.     private final Gate gate;
  49.     private final String myName;
  50.     private final String myAddress;
  51.     public UserThread(Gate gate, String myName, String myAddress) {
  52.         this.gate = gate;
  53.         this.myName = myName;
  54.         this.myAddress = myAddress;
  55.     }
  56.     public void run() {
  57.         while (true) {
  58.             System.out.println(myName + "  passing");
  59.             gate.pass(myName, myAddress);
  60.         }
  61.     }
  62. }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值