2

java | 静态代理

 1 year ago
source link: https://benpaodewoniu.github.io/2022/11/19/java55/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

java | 静态代理

2022-11-19java进阶多线程

2

有一个疑问,就是,为什么线程的开启长下面这样。

new Thread(() -> System.out.println(1)).start();

有这样一个场景。

你去饭店吃饭,会有厨师给你做菜,本来你不去饭店,是你自己做饭,但是,你去饭店,是厨师给你做饭,你付钱。

这是不是相当于厨师代理你做了饭。

写成代码如下。

package com.example.blog;

import lombok.SneakyThrows;

import java.util.concurrent.*;

interface Cook {
void cook();
}

class Customer implements Cook {
@Override
public void cook() {
System.out.println("客户吃饭");
}
}

class Chef implements Cook {

public Cook target;

public Chef(Cook cook) {
target = cook;
}

@Override
public void cook() {
before();
target.cook();
}

private void before() {
System.out.println("客户下单");
}
}

public class T {
public static void main(String[] args){
// 第一种方式
Customer customer = new Customer();
new Chef(customer).cook();
// 第二种方式
new Chef(() -> System.out.println("客户吃饭")).cook();
}
}

代码中第二种方式是不是和线程开启特别像。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK