用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. nginx 访问控制之 document_uri

    这就用到了变量$document_uri,根据前面所学内容,该变量等价于$uri,其实也等价于location匹配. 示例1: if ($document_uri ~ "/admin/&qu ...

  2. win10中通过Anaconda安装tensorflow时报错Traceback (most recent call last): File “E:\Anaconda3\lib\site-packages\pip_vendor\urllib3\response.py”, line 360, in _error_catcher yield

    问题:通过默认镜像安装,下载过程中可能会报错,下载安装失败 Traceback (most recent call last): File “E:\Anaconda3\lib\site-package ...

  3. Java中的long类型和Long类型比较大小

    Java中我们经常要做一些判断,而对于判断的话,用的最多的便是“>”.“==”.“<”的比较,这里我们进行一个Long类型数据和long类型数据的比较大小的讲解. Java中Long和lo ...

  4. attempt to call method 'getDataString' (a nil value)

    错误: LUA ERROR: [: attempt to call method 'getDataString' (a nil value) 在合并cocos和quick的时候,在EventCusto ...

  5. 深入分析Synchronized原理(阿里面试题)

    还有一篇 讲解lock的实现原理,参考:解决多线程安全问题-无非两个方法synchronized和lock 具体原理以及如何 获取锁AQS算法 (百度-美团) 记得开始学习Java的时候,一遇到多线程 ...

  6. 剑指offer:把数组排成最小的数

    题目描述: 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个.例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323. 思路分析: ...

  7. Python中如何计算字符串里面某一个字符出现的次数?

    一个突发奇想,想解决一个学习中的行业痛点,让我又再度拾起了Python编程语言的学习.   刚学两天,今天遇到一个题,该题难度不高,但有一点关键点在网上找不到,网上也没有相关的答案,于是我只好千辛万苦 ...

  8. adb server version (31) doesn't match this client (41); killing...

    1.有时候用adb工具去连接安卓设备,或者模拟器的时候,会提示adb server version(31) doesn’t match this client(41)这样的提示.如图 提示的字面意思就 ...

  9. Unity3D普通开发人员,U3D主程分别需要掌握的技能

    Unity3D普通开发人员 1.会查看和搜索unity API文档,熟悉一些3D术语单词 2.查看别人的代码,能够依葫芦画瓢 3.能够制作一些常见的UI效果,善用缓动类插件,如Do Tween pro ...

  10. git推送本地分支到远程仓库并在远程仓库创建新分支

    $ git push <远程主机名> <本地分支名>:<远程分支名> git push master test:test #master 为设置的远程仓库别名,第一 ...