静态代理

来源:互联网 发布:如何投诉淘宝客服态度 编辑:程序博客网 时间:2024/06/18 07:19
  • 静态代理实现
  • 1.定义真实类 PickTicket 并实现 Runnable 接口
  • 2.定义代理类 (例如系统标准的进程类:Thread) 并把 真实类 PickTicket 传入代理类汇总
  • 4.代理类调用 start 启动进程
  • *

真实类 PickTicket

package cn.thread;/** * @author Duoduo * @version 1.0 * @date 2017/4/19 15:25 */public class PickTicket implements Runnable {    private int ticketNumber = 100;    private  boolean flag = true;    @Override    public void run() {        System.out.println(Thread.currentThread().getName());        while (flag) {            test1();        }    }    private synchronized void test2() {        if (ticketNumber <= 0) {            flag = false;            return;        }        try {            Thread.sleep(1);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println(Thread.currentThread().getName() + " get the ticket :" + " " + ticketNumber--);    }    private void test1() {        if (ticketNumber <= 0) {            flag = false;            return;        }        try {            Thread.sleep(1);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println(Thread.currentThread().getName() + " get the ticket :" + " " + ticketNumber--);    }}

测试类 Test1

package cn.thread;/** * 静态代理实现 * 1.定义真实类 PickTicket 并实现 Runnable 接口 * 2.定义代理类 (例如系统标准的进程类:Thread) 并把 真实类 PickTicket 传入代理类汇总 * 4.代理类调用 start 启动进程 * * @author Duoduo * @version 1.0 * @date 2017/4/19 15:25 */public class Test1 {    public static void main(String[] args) {        PickTicket ticket = new PickTicket();        Thread proxy1 = new Thread(ticket, "路人甲");        Thread proxy2 = new Thread(ticket, "黄牛乙");        Thread proxy3 = new Thread(ticket, "攻城狮");        proxy1.start();        proxy2.start();        proxy3.start();    }}

测试结果:

路人甲黄牛乙攻城狮路人甲 get the ticket : 10黄牛乙 get the ticket : 9攻城狮 get the ticket : 8路人甲 get the ticket : 7黄牛乙 get the ticket : 6攻城狮 get the ticket : 5路人甲 get the ticket : 4黄牛乙 get the ticket : 3攻城狮 get the ticket : 2路人甲 get the ticket : 1攻城狮 get the ticket : 0黄牛乙 get the ticket : -1
0 0
原创粉丝点击