ThreadPoolExecutor组合使用synchronized关键字

未加synchronized关键字:

package com.allen.thread;

import java.util.concurrent.*;

/**
 * @author :jhys
 * @date :Created in 2021/7/23 16:33
 * @Description :
 */
public class SynchronizedTest {

    public static void main(String[] args) {
        // 创建 Runnable实现类的实例,并依此实例作为Thread的target来创建Thread对象
        RunTask task = new RunTask();
        // 使用ThreadPoolExecutor手动创建线程池,coreThreadPoolSize设置为20, 一次性启动20个线程来执行提交的100个任务
        ExecutorService pool = new ThreadPoolExecutor(20, 100, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(1000));

        for (int i = 0; i < 100; i++) {
            pool.submit(new Thread(task));
        }
    }

}

/**
 * 实现Runnable接口
 */
class RunTask implements Runnable {
    private int i = 100;

    @Override
    public  void run() {
        try {
            if (i > 0) {
                i--;
                System.out.println(i + " "+ Thread.currentThread().getName());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

结果:

97 pool-1-thread-2
96 pool-1-thread-4
97 pool-1-thread-3
97 pool-1-thread-1
95 pool-1-thread-6
94 pool-1-thread-5
93 pool-1-thread-7
92 pool-1-thread-10
91 pool-1-thread-9
90 pool-1-thread-8
89 pool-1-thread-11
88 pool-1-thread-12
87 pool-1-thread-13
86 pool-1-thread-14
85 pool-1-thread-15
84 pool-1-thread-16
83 pool-1-thread-17
82 pool-1-thread-18
81 pool-1-thread-2
80 pool-1-thread-1
79 pool-1-thread-1
77 pool-1-thread-4
78 pool-1-thread-3
71 pool-1-thread-9
68 pool-1-thread-11
69 pool-1-thread-3
66 pool-1-thread-3
65 pool-1-thread-17
61 pool-1-thread-2
70 pool-1-thread-8
72 pool-1-thread-10
73 pool-1-thread-4
74 pool-1-thread-5
75 pool-1-thread-6
76 pool-1-thread-1
46 pool-1-thread-6
47 pool-1-thread-5
48 pool-1-thread-4
49 pool-1-thread-14
50 pool-1-thread-16
51 pool-1-thread-17
52 pool-1-thread-10
38 pool-1-thread-10
53 pool-1-thread-7
55 pool-1-thread-11
54 pool-1-thread-8
56 pool-1-thread-9
34 pool-1-thread-8
57 pool-1-thread-2
58 pool-1-thread-13
59 pool-1-thread-12
60 pool-1-thread-20
62 pool-1-thread-19
63 pool-1-thread-18
64 pool-1-thread-3
67 pool-1-thread-15
25 pool-1-thread-3
26 pool-1-thread-18
27 pool-1-thread-19
28 pool-1-thread-20
29 pool-1-thread-12
19 pool-1-thread-12
30 pool-1-thread-13
31 pool-1-thread-2
32 pool-1-thread-8
33 pool-1-thread-9
35 pool-1-thread-11
13 pool-1-thread-11
36 pool-1-thread-7
11 pool-1-thread-7
37 pool-1-thread-10
39 pool-1-thread-17
40 pool-1-thread-16
7 pool-1-thread-16
41 pool-1-thread-14
42 pool-1-thread-4
43 pool-1-thread-5
44 pool-1-thread-6
45 pool-1-thread-1
2 pool-1-thread-6
3 pool-1-thread-5
4 pool-1-thread-4
5 pool-1-thread-14
6 pool-1-thread-16
8 pool-1-thread-17
9 pool-1-thread-10
10 pool-1-thread-7
12 pool-1-thread-11
14 pool-1-thread-9
15 pool-1-thread-8
16 pool-1-thread-2
17 pool-1-thread-13
18 pool-1-thread-12
20 pool-1-thread-20
21 pool-1-thread-19
22 pool-1-thread-18
23 pool-1-thread-3
24 pool-1-thread-15
0 pool-1-thread-6
1 pool-1-thread-1

打印结果完全错乱,因为没有使用同步锁!

加入synchronized关键字:

package com.allen.thread;

import java.util.concurrent.*;

/**
 * @author :jhys
 * @date :Created in 2021/7/23 16:33
 * @Description :
 */
public class SynchronizedTest {

    public static void main(String[] args) {
        // 创建 Runnable实现类的实例,并依此实例作为Thread的target来创建Thread对象
        RunTask task = new RunTask();
        // 使用ThreadPoolExecutor手动创建线程池,coreThreadPoolSize设置为20, 一次性启动20个线程来执行提交的100个任务
        ExecutorService pool = new ThreadPoolExecutor(20, 100, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(1000));

        for (int i = 0; i < 100; i++) {
            pool.submit(new Thread(task));
        }
        pool.shutdown();
    }

}

/**
 * 实现Runnable接口
 */
class RunTask implements Runnable {
    private int i = 100;

    @Override
    public synchronized void run() {
        try {
            if (i > 0) {
                i--;
                System.out.println(i + " "+ Thread.currentThread().getName());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

或者:

package com.allen.thread;

import java.util.concurrent.*;

/**
 * @author :jhys
 * @date :Created in 2021/7/23 16:33
 * @Description :
 */
public class SynchronizedTest {

    public static void main(String[] args) {
        // 创建 Runnable实现类的实例,并依此实例作为Thread的target来创建Thread对象
        RunTask task = new RunTask();
        // 使用ThreadPoolExecutor手动创建线程池,coreThreadPoolSize设置为20, 一次性启动20个线程来执行提交的100个任务
        ExecutorService pool = new ThreadPoolExecutor(20, 100, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(1000));

        for (int i = 0; i < 100; i++) {
            pool.submit(new Thread(task));
        }
        pool.shutdown();
    }

}

/**
 * 实现Runnable接口
 */
class RunTask implements Runnable {
    private int i = 100;

    @Override
    public  void run() {
        synchronized (this) {
            try {
                if (i > 0) {
                    i--;
                    System.out.println(i + " "+ Thread.currentThread().getName());
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

或者:

package com.allen.thread;

import java.util.concurrent.*;

/**
 * @author :jhys
 * @date :Created in 2021/7/23 16:33
 * @Description :
 */
public class SynchronizedTest {

    public static void main(String[] args) {
        // 创建 Runnable实现类的实例,并依此实例作为Thread的target来创建Thread对象
        RunTask task = new RunTask();
        // 使用ThreadPoolExecutor手动创建线程池,coreThreadPoolSize设置为20, 一次性启动20个线程来执行提交的100个任务
        ExecutorService pool = new ThreadPoolExecutor(20, 100, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(1000));

        for (int i = 0; i < 100; i++) {
            pool.submit(new Thread(task));
        }
        pool.shutdown();
    }

}

/**
 * 实现Runnable接口
 */
class RunTask implements Runnable {
    Object lock = new Object();
    private int i = 100;

    @Override
    public  void run() {
        synchronized (lock) {
            try {
                if (i > 0) {
                    i--;
                    System.out.println(i + " "+ Thread.currentThread().getName());
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

或者:

package com.allen.thread;

import java.util.concurrent.*;

/**
 * @author :jhys
 * @date :Created in 2021/7/23 16:33
 * @Description :
 */
public class SynchronizedTest {

    public static void main(String[] args) {
        // 创建 Runnable实现类的实例,并依此实例作为Thread的target来创建Thread对象
        RunTask task = new RunTask();
        // 使用ThreadPoolExecutor手动创建线程池,coreThreadPoolSize设置为20, 一次性启动20个线程来执行提交的100个任务
        ExecutorService pool = new ThreadPoolExecutor(20, 100, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(1000));

        for (int i = 0; i < 100; i++) {
            pool.submit(new Thread(task));
        }
        pool.shutdown();
    }

}

/**
 * 实现Runnable接口
 */
class RunTask implements Runnable {
    Object lock = new Object();
    private int i = 100;

    @Override
    public  void run() {
        synchronized (RunTask.class) {
            try {
                if (i > 0) {
                    i--;
                    System.out.println(i + " "+ Thread.currentThread().getName());
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

上述写法都能实现同步,结果如下,

99 pool-1-thread-1
98 pool-1-thread-4
97 pool-1-thread-6
96 pool-1-thread-3
95 pool-1-thread-2
94 pool-1-thread-8
93 pool-1-thread-7
92 pool-1-thread-5
91 pool-1-thread-10
90 pool-1-thread-9
89 pool-1-thread-11
88 pool-1-thread-12
87 pool-1-thread-13
86 pool-1-thread-14
85 pool-1-thread-15
84 pool-1-thread-16
83 pool-1-thread-17
82 pool-1-thread-18
81 pool-1-thread-19
80 pool-1-thread-20
79 pool-1-thread-1
78 pool-1-thread-2
77 pool-1-thread-7
76 pool-1-thread-9
75 pool-1-thread-12
74 pool-1-thread-13
73 pool-1-thread-8
72 pool-1-thread-1
71 pool-1-thread-9
70 pool-1-thread-16
69 pool-1-thread-3
68 pool-1-thread-6
67 pool-1-thread-4
66 pool-1-thread-3
65 pool-1-thread-6
64 pool-1-thread-9
63 pool-1-thread-16
62 pool-1-thread-14
61 pool-1-thread-20
60 pool-1-thread-8
59 pool-1-thread-12
58 pool-1-thread-15
57 pool-1-thread-1
56 pool-1-thread-19
55 pool-1-thread-18
54 pool-1-thread-13
53 pool-1-thread-17
52 pool-1-thread-11
51 pool-1-thread-7
50 pool-1-thread-7
49 pool-1-thread-7
48 pool-1-thread-7
47 pool-1-thread-10
46 pool-1-thread-5
45 pool-1-thread-2
44 pool-1-thread-5
43 pool-1-thread-10
42 pool-1-thread-10
41 pool-1-thread-10
40 pool-1-thread-7
39 pool-1-thread-11
38 pool-1-thread-17
37 pool-1-thread-13
36 pool-1-thread-18
35 pool-1-thread-19
34 pool-1-thread-1
33 pool-1-thread-15
32 pool-1-thread-12
31 pool-1-thread-12
30 pool-1-thread-8
29 pool-1-thread-20
28 pool-1-thread-20
27 pool-1-thread-20
26 pool-1-thread-20
25 pool-1-thread-20
24 pool-1-thread-20
23 pool-1-thread-20
22 pool-1-thread-20
21 pool-1-thread-20
20 pool-1-thread-20
19 pool-1-thread-20
18 pool-1-thread-14
17 pool-1-thread-16
16 pool-1-thread-9
15 pool-1-thread-6
14 pool-1-thread-3
13 pool-1-thread-4
12 pool-1-thread-8
11 pool-1-thread-12
10 pool-1-thread-15
9 pool-1-thread-1
8 pool-1-thread-19
7 pool-1-thread-18
6 pool-1-thread-13
5 pool-1-thread-17
4 pool-1-thread-11
3 pool-1-thread-7
2 pool-1-thread-10
1 pool-1-thread-5
0 pool-1-thread-2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CompletableFuture和ThreadPoolExecutor组合是一种常见的方式,用于在异步编程中执行并发任务并处理结果。 CompletableFuture是Java 8引入的一个类,用于支持异步编程和任务组合。它提供了一组方法来执行异步操作,并在操作完成时处理结果。ThreadPoolExecutorJava提供的一个线程池实现,用于管理和执行线程。 使用CompletableFuture和ThreadPoolExecutor组合,你可以将任务提交给线程池进行并发执行,并使用CompletableFuture来处理任务的结果。下面是一个简单的示例: ```java import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; public class CompletableFutureWithThreadPoolExample { public static void main(String[] args) { // 创建一个线程池 ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5); // 提交任务给线程池执行,并返回CompletableFuture对象 CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { // 执行耗时操作 return "Task Result"; }, executor); // 处理任务结果 future.thenAccept(result -> { System.out.println("Task Result: " + result); // 执行其他操作 }); // 关闭线程池 executor.shutdown(); } } ``` 在上面的示例中,我们创建了一个线程池,并使用`supplyAsync()`方法将任务提交给线程池进行异步执行。然后,我们使用`thenAccept()`方法来处理任务的结果。最后,我们关闭了线程池。 通过这种方式,你可以同时执行多个任务,并在任务完成时处理它们的结果。你还可以使用CompletableFuture的其他方法来进行任务组合、异常处理等操作。 希望这个示例对你有所帮助!如果你还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值