Java非算法手撕

线程池

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class Solution {
public static void main(String[] args) {
int corePoolSize = 2;
int maximumPoolSize = 4;
long keepAliveTime = 10L;

ThreadPoolExecutor pool = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(),
new CustomThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);

// 提交任务到线程池
for (int i = 0; i < 10; i++) {
pool.execute(new Task(i));
}

// 关闭线程池
pool.shutdown();
try {
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow();
}
} catch (InterruptedException ex) {
pool.shutdownNow();
Thread.currentThread().interrupt();
}
}
}

class CustomThreadFactory implements ThreadFactory {
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix = "pool-";

@Override
public Thread newThread(Runnable r) {
return new Thread(r, namePrefix + threadNumber.getAndIncrement());
}
}

class Task implements Runnable {
private final int taskId;

public Task(int taskId) {
this.taskId = taskId;
}

@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is executing task " + taskId);
try {
Thread.sleep(2000); // 模拟任务执行时间
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

JDK动态代理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface UserService {
void print();
}

class UserServiceImpl implements UserService {
@Override
public void print() {
System.out.println("user");
}
}

class Handler implements InvocationHandler {
public final Object target;
public Handler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before");
Object res = method.invoke(target, args);
System.out.println("after");
return res;
}
}

public class Main{
public static void main(String[] args) {
UserServiceImpl service = new UserServiceImpl();
UserService proxy = (UserService)Proxy.newProxyInstance(
service.getClass().getClassLoader(),
service.getClass().getInterfaces(),
new Handler(service));
proxy.print();
}
}

CompletableFuture使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.concurrent.CompletableFuture;

public class Main {
public static void main(String[] args) {
CompletableFuture<Void> cf1 = CompletableFuture.runAsync(() -> {
try {
System.out.println("cf1");
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore the interrupted status
System.err.println("Task was interrupted: " + e.getMessage());
}
});
CompletableFuture<Void> cf2 = CompletableFuture.runAsync(() -> {
try {
System.out.println("cf2");
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore the interrupted status
System.err.println("Task was interrupted: " + e.getMessage());
}
});
CompletableFuture<Void> bothComplete = CompletableFuture.allOf(cf1, cf2);
bothComplete.thenRunAsync(() -> {
try {
System.out.println("both");
Thread.sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore the interrupted status
System.err.println("Task was interrupted: " + e.getMessage());
}
});

bothComplete.join();
}
}

单例模式构建和测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Singleton {
private Singleton() {}
public static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

public class Main{

public static void main(String[] args) throws InterruptedException {
final int threadCnt = 100;
ExecutorService executor = Executors.newFixedThreadPool(threadCnt);
CountDownLatch latch = new CountDownLatch(threadCnt);
Singleton[] instances = new Singleton[threadCnt];
for (int i = 0; i < threadCnt; i++) {
final int idx = i;
executor.submit(() -> {
try {
latch.await(); // 确保所有线程准备好,再释放
instances[idx] = Singleton.getInstance();
} catch(InterruptedException e) {
e.printStackTrace();
}
});
latch.countDown();
}
executor.shutdown(); // 关闭线程池,停止接受新任务
while (!executor.isTerminated()) { // 轮询检查线程池是否完全终止
Thread.sleep(100); // 避免忙等待(Busy Waiting),减少 CPU 占用
}
// 所有任务完成后,继续执行后续验证代码
Object expected = Singleton.getInstance();
for (Object obj : instances) {
if (obj != expected) {
System.out.println("not equal");
return;
}
}
System.out.println("equal");
}
}