java多线程的使用

个人的使用经验,水平比较低,仅供记录

1.多线程是什么?

我觉得:线程就是同时间点的并发运行程序;多线程就是多个线程。。。额,是的吧

2.多线程的使用场景

我觉得:1.允许并发执行的场景,   2.多个线程处理大数据量

3.如何解决同步并发问题

我觉得:参考vector后可以发现,所谓的同步就是在其map的方法上添加了synchronized,解决的问题就是多个线程间同步问题,实际就是当某个线程处理同步方法时,其他线程阻塞状态,

所以达到多线程的同步方法或同步代码块的线性执行;

单服务器情况下,代码中处理数据源的多线程并发问题,synchronized可以解决

分布式开发时,就会出现分布式并发问题,需要在数据源做锁操作

测试案例:

C3p0链接配置文件:config.properties

DriverClass = com.mysql.cj.jdbc.Driver
JdbcUrl = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
User = root
Password = 123456
MaxPoolSize = 20
MinPoolSize = 2
InitialPoolSize = 5
MaxStatements = 30
MaxIdleTime =100

 

连接池


import java.sql.Connection;
import java.util.Properties;
import com.mchange.v2.c3p0.ComboPooledDataSource;

/*
 * @author 22923
 * @date 创建时间 2018年5月13日
 * @description 通过配置文件的形式,建立对C3P0的操作,
 */
public class C3p0Msql {

    private ComboPooledDataSource cpds;

    private static C3p0Msql c3P0Properties;

    static{
        c3P0Properties = new C3p0Msql();
    }

    public C3p0Msql() {
        try {
            cpds = new ComboPooledDataSource();

            //加载配置文件
            Properties props = new Properties();
            props.load(C3p0Msql.class.getClassLoader().getResourceAsStream("config.properties"));

            cpds.setDriverClass(props.getProperty("DriverClass"));
            cpds.setJdbcUrl(props.getProperty("JdbcUrl"));
            cpds.setUser(props.getProperty("User"));
            cpds.setPassword(props.getProperty("Password"));

            cpds.setMaxPoolSize(Integer.parseInt(props.getProperty("MaxPoolSize")));
            cpds.setMinPoolSize(Integer.parseInt(props.getProperty("MinPoolSize")));
            cpds.setInitialPoolSize(Integer.parseInt(props.getProperty("InitialPoolSize")));
            cpds.setMaxStatements(Integer.parseInt(props.getProperty("MaxStatements")));
            cpds.setMaxIdleTime(Integer.parseInt(props.getProperty("MaxIdleTime")));

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

    public static C3p0Msql getInstance(){
        return c3P0Properties;
    }

    public Connection getConnection(){
        Connection conn = null;
        try {
            conn = cpds.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Connection connection = C3p0Msql.c3P0Properties.getConnection();
        System.out.println("已经连接成功");

    }

}

 

 

Dao

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TrickDao {
    private Connection connection;
    public TrickDao(Connection connection){
        this.connection=connection;
    }
    public synchronized int gettrick(){
        try {
           // C3p0Msql c3p0Msql = C3p0Msql.getInstance();
           // Connection connection = c3p0Msql.getConnection();
            Statement state = connection.createStatement();
            ResultSet set = state.executeQuery("SELECT trick_count FROM trick ");
            boolean rs = set.next();
            int trick_count=0;
            if(rs){
                String str= set.getString("trick_count");
                trick_count=Integer.valueOf(str);
              //  connection.close();
            }
            return trick_count;

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    public synchronized void setTrick(){
        try {

            Statement state = connection.createStatement();
           // boolean execute = state.execute("UPDATE trick SET trick_count=trick_count-1 WHERE id=1 ");
            int count=state.executeUpdate("UPDATE trick SET trick_count=trick_count-1 WHERE id=1 ");
           // connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }


}

线程

import java.sql.Connection;
import java.util.Date;

public class ThreadTest1 extends Thread{
    TrickDao trick;
    public ThreadTest1(TrickDao trick){
        this.trick=trick;
    }


    @Override
    public void run() {
       // int count=trick.gettrick();f
        while(trick.gettrick()>0){
            int count=trick.gettrick();
            trick.setTrick();
            System.out.println(Thread.currentThread().getId() + "当前售票" +count);
        }

        if(trick.gettrick()==0){
            Date date=new Date();
            System.out.println("end:"+" -- "+" -"+System.currentTimeMillis());
        }


     }



}

 

测试main入口

import org.springframework.jdbc.datasource.ConnectionHolder;

import java.sql.Connection;
import java.util.Date;
import java.util.Vector;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test1 {
    public static void main(String[] args) {


        C3p0Msql c3p0Msql = C3p0Msql.getInstance();
        Connection connect = c3p0Msql.getConnection();

        TrickDao trickDao=new TrickDao(connect);


        System.out.println("已经连接成功");

      //  ExecutorService executorService= Executors.newFixedThreadPool(4);
        Date date=new Date();
        System.out.println("star4t:"+" -- "+" -"+System.currentTimeMillis());
        ThreadTest1 thread1=new ThreadTest1(trickDao);
        ThreadTest1 thread2=new ThreadTest1(trickDao);
        ThreadTest1 thread3=new ThreadTest1(trickDao);
        ThreadTest1 thread4=new ThreadTest1(trickDao);

                thread1.start();
                thread2.start();
        thread3.start();
        thread4.start();
       // executorService.submit(thread1);


    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值