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 就是代理类