多线程03 线程中的静态代理

博客介绍了静态代理的角色分析,包括抽象接口、真实对象、代理对象和客户。指出代理对象会对真实角色进行代理并附带附属操作,还总结得出线程中运用的是静态代理模式,Thread 为代理类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、静态代理
角色分析

  • 抽象接口
@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}
  • 真实对象:
public class MyRunnable implements Runnable{
    public void run() {
        System.out.println("线程体");
    }
}
  • 代理对象:代理真实角色,一般会有些附属操作
public class Thread implements Runnable {

    private Runnable target;

    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }

    public void run() {
        if (target != null) {
            target.run();
        }
    }

}
  • 客户:访问代理对象的人
public class Test01 {
    public static void main(String[] args) {
        // 真实对象
        MyRunnable runnable = new MyRunnable();
        // 代理对象
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

总结:由此可以看出,线程中用的是静态代理模式,Thread 就是代理类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值