首页 > 代码库 > 读Java并发编程实践中,向已有线程安全类添加功能--客户端加锁实现示例
读Java并发编程实践中,向已有线程安全类添加功能--客户端加锁实现示例
在Java并发编程实践中4.4中提到向客户端加锁的方法。此为验证示例,写的不好,但可以看出结果来。
package com.blackbread.test;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class GoodListHelper<E> { public List<E> list = Collections.synchronizedList(new ArrayList<E>()); public boolean putIfAbsent(E x) throws InterruptedException { synchronized (list) { boolean absent = !list.contains(x); if (absent) { if (list.contains(x)) System.out.println(list.contains(x)); list.add(x); } return absent; } } public class PrintA extends Thread { private GoodListHelper<String> goodListHelper; private String value; public PrintA(GoodListHelper<String> goodListHelper, String value) { this.goodListHelper = goodListHelper; this.value =http://www.mamicode.com/ value; } @Override public void run() { try { goodListHelper.putIfAbsent(value); } catch (InterruptedException e) { e.printStackTrace(); } } } public class PrintB extends Thread { private GoodListHelper<String> goodListHelper; private String value; public PrintB(GoodListHelper<String> goodListHelper, String value) { this.goodListHelper = goodListHelper; this.value =http://www.mamicode.com/ value; } @Override public void run() { goodListHelper.list.add(value); } } public static void main(String[] args) throws InterruptedException { final GoodListHelper<String> goodListHelper = new GoodListHelper<String>(); new Thread(new Runnable() { @Override public void run() { ExecutorService executor = Executors.newFixedThreadPool(50); for (int i = 0; i < 1000; i++) { Thread t = goodListHelper.new PrintA(goodListHelper, String.valueOf(i)); executor.execute(t); } executor.shutdown(); } }).start(); new Thread(new Runnable() { @Override public void run() { ExecutorService executor = Executors.newFixedThreadPool(50); for (int i = 0; i < 1000; i++) { Thread t = goodListHelper.new PrintB(goodListHelper, String.valueOf(i)); executor.execute(t); } executor.shutdown(); } }).start(); }}
读Java并发编程实践中,向已有线程安全类添加功能--客户端加锁实现示例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。