用Condition和synchronized:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; public class MyDataSource {
// 不停的增删改
private LinkedList<Connection> pool = new LinkedList<>();
private static final int INIT_CONNECTIONS = 10;
private static final String DRIVER_CLASS = "";
private static final String USER = "";
private static final String PASSWORD = "";
private static final String URL = ""; private Lock lock = new ReentrantLock();
private Condition c1 = lock.newCondition(); static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} public MyDataSource() {
for (int i = 0; i < INIT_CONNECTIONS; i++) {
try {
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
pool.addLast(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
} public Connection getConnection() {
Connection result = null;
lock.lock();
try {
while (pool.size() <= 0) {
try {
c1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (!pool.isEmpty()) {
result = pool.removeFirst();
} return result;
} finally {
lock.unlock();
}
} public Connection getConnectionSynchronized() {
Connection result = null;
synchronized (pool) {
while (pool.size() <= 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (!pool.isEmpty()) {
result = pool.removeFirst();
}
}
return result;
}
public void release(Connection conn){
if(conn!=null){
lock.lock();
try {
pool.addLast(conn);
c1.signal();
} finally {
lock.unlock();
}
}
}
public void releaseSynchronized(Connection conn) {
if (conn != null) {
synchronized (pool) {
pool.addLast(conn);
notifyAll();
}
}
}
}

  线程之间的通信-join

public class Demo {
public void a(Thread joinThread){
System.out.println("方法a执行了。。。。");
joinThread.start();
try {
joinThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("a方法执行完毕。。。");
}
public void b(){
System.out.println("加塞线程开始执行");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("加塞线程执行完毕...");
}
public static void main(String[] args) {
Demo demo=new Demo();
Thread joinThread=new Thread(new Runnable() {
@Override
public void run() {
demo.b();
}
});
new Thread(new Runnable() {
@Override
public void run() {
demo.a(joinThread);
}
}).start();
}
}

  ThreadLocal:

public class Demo99 {
private ThreadLocal<Integer> count =
new ThreadLocal<Integer>() {
protected Integer initialValue() {
return new Integer(0);
};
}; public int getNext() {
Integer value = count.get();
value++;
count.set(value);
return value;
} public static void main(String[] args) {
Demo99 d=new Demo99();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println(
Thread.currentThread().getName() + " " +
d.getNext());
try {
Thread.sleep(1000);
} catch (InterruptedException e) { e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println(
Thread.currentThread().getName() + " " +
d.getNext());
try {
Thread.sleep(1000);
} catch (InterruptedException e) { e.printStackTrace();
}
}
}
}).start(); }
}

  线程之间的通讯:CountDownLatch

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; public class Demo {
private int[] nums; public Demo(int line) {
nums = new int[line];
} public void calc(String line, int index) { String[] nus = line.split(",");// 切分出每一个值
int total = 0;
for (String num : nus) {
total += Integer.parseInt(num);
}
nums[index] = total;// 把计算的结果放到数组中指点的位置
System.out.println(Thread.currentThread().getName() + "行计划任务...." + line + "结果为:" + total);
} public void sum() {
System.out.println("汇总线程开始执行....");
int total = 0;
for (int i = 0; i < nums.length; i++) {
total += nums[i];
}
System.out.println("最终的结果为:" + total);
} public static void main(String[] args) {
List<String> contents = readFile();
int lineCount = contents.size();
Demo d = new Demo(lineCount);
for (int i = 0; i < lineCount; i++) {
final int j = i;
new Thread(new Runnable() {
@Override
public void run() {
d.calc(contents.get(j), j);
}
}).start();
}
while (Thread.activeCount() > 1) { }
d.sum();
} private static List<String> readFile() {
List<String> contents = new ArrayList<>();
String line = null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("e:\\num.txt"));
while ((line = br.readLine()) != null) {
contents.add(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return contents;
}
}

  

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch; public class Demo2 {
private int[] nums; public Demo2(int line) {
nums = new int[line];
} public void calc(String line, int index,CountDownLatch latch) { String[] nus = line.split(",");// 切分出每一个值
int total = 0;
for (String num : nus) {
total += Integer.parseInt(num);
}
nums[index] = total;// 把计算的结果放到数组中指点的位置
System.out.println(Thread.currentThread().getName() + "行计划任务...." + line + "结果为:" + total);
latch.countDown();
} public void sum() {
System.out.println("汇总线程开始执行....");
int total = 0;
for (int i = 0; i < nums.length; i++) {
total += nums[i];
}
System.out.println("最终的结果为:" + total);
} public static void main(String[] args) {
List<String> contents = readFile();
int lineCount = contents.size();
CountDownLatch latch=new CountDownLatch(lineCount);
Demo2 d = new Demo2(lineCount);
for (int i = 0; i < lineCount; i++) {
final int j = i;
new Thread(new Runnable() {
@Override
public void run() {
d.calc(contents.get(j), j,latch);
}
}).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
d.sum();
} private static List<String> readFile() {
List<String> contents = new ArrayList<>();
String line = null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("e:\\num.txt"));
while ((line = br.readLine()) != null) {
contents.add(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return contents;
}
}

  线程之间的通信:CyclicBarrier  达到屏障点之后,后面的线程才继续执行

import java.util.Random;
import java.util.concurrent.CyclicBarrier; public class Demo {
Random random = new Random(); public void meeting(CyclicBarrier barrier) {
try {
Thread.sleep(random.nextInt(4000));
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "到达会议室,等待开会...");
if(Thread.currentThread().getName().equals("Thread-1")){
throw new RuntimeException();
}
try {
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"发言");
} public static void main(String[] args) {
Demo demo = new Demo();
CyclicBarrier barrier = new CyclicBarrier(10, new Runnable() {
@Override
public void run() {
System.out.println("好,我们开始开会.....");
}
});
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
demo.meeting(barrier);
}
}).start();
}
}
}  

线程之间的通讯:Semaphore:能控制被多少个线程同时访问

import java.util.concurrent.Semaphore;

public class Demo22 {
public void method(Semaphore semaphore){
try {
semaphore.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"is run...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
semaphore.release();
}
public static void main(String[] args) {
Demo22 d=new Demo22();
Semaphore semaphore=new Semaphore(10);
while (true) {
new Thread(new Runnable() {
@Override
public void run() {
d.method(semaphore);
}
}).start(); }
}
}

  Exchanger:

import java.util.concurrent.Exchanger;

public class Demo33 {
public void a(Exchanger<String> exch){
System.out.println("a 方法执行....");
try {
System.out.println("a 线程正在抓取数据....");
Thread.sleep(2000);
System.out.println("a 抓取到数据.....");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String res="12345";
try {
System.out.println("等待对比结果....");
exch.exchange(res);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void b(Exchanger<String> exch){
System.out.println("b 方法开始执行....");
try {
System.out.println("b 方法开始抓取数据....");
Thread.sleep(4000);
System.out.println("b 方法抓取数据结束....");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String res="12345";
try {
String value=exch.exchange(res);
System.out.println("开始进行比对.....");
System.out.println("比对结果为:"+value.equals(res)); } catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Demo33 d=new Demo33();
Exchanger<String> exch=new Exchanger<>();
new Thread(new Runnable() {
@Override
public void run() {
d.a(exch);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
d.b(exch);
}
}).start();
}
}

  提前完成任务Future使用:

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask; public class Demo44 {
public static void main(String[] args) throws Exception{
Callable<Integer> call=new Callable<Integer>() {
@Override
public Integer call() throws Exception{
System.out.println("正在计算结果....");
Thread.sleep(3000);
return 1;
}
};
FutureTask<Integer> task=new FutureTask<>(call);
Thread thread=new Thread(task);
thread.start(); //do something
System.out.println("干点别的...");
Integer result=task.get();
System.out.println("拿到的结果为:"+result);
}
}

  用买蛋糕和去上班的例子说明 :

public class Product {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Product [id="+id+",name="+name+"]";
}
public Product(int id,String name) {
try {
System.out.println("开始生产"+name);
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.id=id;
this.name=name;
System.out.println(name+"生产完毕");
}
}

  

public class Future {
private Product product;
private boolean down;
public synchronized void setProduct(Product product){
if(down) return; this.product=product;
this.down=true;
notifyAll();
}
public synchronized Product get(){
while(!down){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return product;
}
}

  

import java.util.Random;

public class ProductFactory {
public Future createProduct(String name){
Future f=new Future();//创建一个订单
System.out.println("下单成功,你可以去上班了...");
//生产产品
new Thread(new Runnable() {
@Override
public void run() {
Product p=new Product(new Random().nextInt(), name);
f.setProduct(p);
}
}).start(); return f;
}
}

  

import java.util.Random;

public class ProductFactory {
public Future createProduct(String name){
Future f=new Future();//创建一个订单
System.out.println("下单成功,你可以去上班了...");
//生产产品
new Thread(new Runnable() {
@Override
public void run() {
Product p=new Product(new Random().nextInt(), name);
f.setProduct(p);
}
}).start(); return f;
}
}

  Callalbe和Runnable的区别:

Runnable run方法是被线程调用的,在run方法是异步执行的

Callable的call方法,不是异步执行的,是由Future的Run方法调用的

ForkJoin:
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask; public class Demo extends RecursiveTask<Integer>{
private int begin;
private int end;
public Demo(int begin,int end){
this.begin=begin;
this.end=end;
}
@Override
protected Integer compute(){
int sum=0; //拆分任务
if(end-begin<=2){
//计算
for(int i=begin;i<=end;i++){
sum+=i;
}
}else{ //拆分
Demo d1=new Demo(begin,(begin+end)/2);
Demo d2=new Demo((begin+end)/2+1,end);
//执行任务
d1.fork();
d2.fork(); Integer a=d1.join();
Integer b=d2.join();
sum=a+b;
}
return sum;
}
public static void main(String[] args) throws Exception {
ForkJoinPool pool=new ForkJoinPool();
ForkJoinTask<Integer> future=pool.submit(new Demo(1,100));
System.out.println("......");
System.out.println("计算的值为:"+future.get());
} }

  

JAVA简易数据连接池Condition的更多相关文章

  1. Java与Scala的两种简易版连接池

    Java版简易版连接池: import java.sql.Connection; import java.sql.DriverManager; import java.util.LinkedList; ...

  2. 数据连接池——JNDI

    数据库连接有很多中方式,JDBC数据库的连接方式,前边我们已经介绍过了,而开发中我们经常使用的是DataBaseConnectionPool(数据库连接池,DBCP).数据库连接池到底是什么?它比jd ...

  3. SpringBoot整合Druid数据连接池

    SpringBoot整合Druid数据连接池 Druid是什么? Druid是Alibaba开源的的数据库连接池.Druid能够提供强大的监控和扩展功能. 在哪里下载druid maven中央仓库: ...

  4. Java基础-DBCP连接池(BasicDataSource类)详解

    Java基础-DBCP连接池(BasicDataSource类)详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 实际开发中“获得连接”或“释放资源”是非常消耗系统资源的两个过程 ...

  5. jdk 动态代理 数据连接池

    package com.itheima.datasource; import java.io.PrintWriter; import java.lang.reflect.InvocationHandl ...

  6. c3p0 数据连接池 流行开源

    注意事项:配置文件规定命名,不能更改   c3p0-config <?xml version="1.0" encoding="UTF-8"?>< ...

  7. Mybatis数据连接池的配置---增删改查(以及遇见的问题)

    1.首先创建项目和各个文件,如图所示: 2.配置相关数据库连接 在jdbc.properties中加入 1 db.driver=com.mysql.jdbc.Driver 2 db.url=jdbc: ...

  8. 数据连接池JNDI

    数据库连接有很多中方式,JDBC数据库的连接方式,前边我们已经介绍过了,而开发中我们经常使用的是DataBaseConnectionPool(数据库连接池,DBCP).数据库连接池到底是什么?它比jd ...

  9. Netbeans 中创建数据连接池和数据源步骤(及解决无法ping通问题)

    1.启动glassfish服务器, 在浏览器的地址栏中输入 http://localhost:4848 2.首先建立JDBC Connection Pools: 3.new 一个Connectio P ...

随机推荐

  1. HTML引入外部JS文件

    <!--引入外部文件的方式--> <script type="text/javascript" src="attack.js">< ...

  2. 实现mysql的读写分离(mysql-proxy)____2

    mysql-proxy简介 MySQL读写分离是指让master处理写操作,让slave处理读操作,非常适用于读操作量比较大的场景,可减轻master的压力. 使用mysql-proxy实现mysql ...

  3. bzoj 3585 mex - 线段树 - 分块 - 莫队算法

    Description 有一个长度为n的数组{a1,a2,...,an}.m次询问,每次询问一个区间内最小没有出现过的自然数. Input 第一行n,m. 第二行为n个数. 从第三行开始,每行一个询问 ...

  4. 《京东上千页面搭建基石——CMS前后端分离演进史》阅读笔记

    一.背景 CMS即内容管理系统,目的是用于快速进行网站建设或者网页开发. 对于京东网站部门来说,CMS核心目的是用来快速开发和上线各种页面,诸如各种垂直频道页. 二.CMS核心目的 进行数据和模板的统 ...

  5. 上传一句话木马时<? php被过滤的解决办法

    i春秋“百度杯”CTF比赛 九月场 web题 upload 题目描述:想怎么传就怎么传,就是这么任性.tips:flag在flag.php中 打开题目发现 于是想到通过上传一句话木马进入后台 上传一句 ...

  6. Ubuntu 14.04下超级终端Minicom连接ARM(转)

    转自:https://blog.csdn.net/ajianyingxiaoqinghan/article/details/70209765 笔者的工作环境: PC系统:Ubuntu 14.04 LT ...

  7. 使用 ArcGIS Desktop 切瓦片

    目录 1.生成切片缓存切片方案 2.切瓦片 1.生成切片缓存切片方案 ArcGIS有默认的切片方案,如果需要自定义切片规则,需要先生成一个切片方案. 打开ArcMap,打开 工具箱(Tools Box ...

  8. nanopi的ds18b20温度传感器测试

    参考(抄袭)资料在这里 先接线,3.3v,gnd,数据输出脚,我是PG11 vim /boot/armbianEnv.txt overlays=w1-gpio param_w1_pin=PG11 pa ...

  9. C# Selenium操作指南,关闭黑色CMD窗口/禁用图片/隐藏浏览器等

    引用部分:1. 2. 配置部分: ChromeDriverService driverService = ChromeDriverService.CreateDefaultService(); dri ...

  10. qt linux 打包

    本文在银河麒麟上成功运行,程序类型:Qt控制台,使用到的Qt外库:mysql数据库 1.环境一共有两台,1是编译机[装有Qt.数据库],2是运行机[纯净机] 2.在编译机上安装Qt.mysql,我这里 ...