多文件多线程断点下载知识点总结

1、数据库多线程访问安全实现

DBHelper.class
public class DBHelper extends SQLiteOpenHelper {
    public static final String DB_NAME="download.db";
    public static final int VERSION=1;
    public static final String SQL_CREATE="create table thread_info(_id integer primary key autoincrement," +
            "thread_id integer,url text,start integer,end integer,finished integer)";
    public static final String SQL_DROP="drop table if exists thread_info";

    private DBHelper(Context context) {
        super(context, DB_NAME , null, VERSION);
    }


    private static DBHelper dbHelper=null;

    /**
     * 单例返回
     * @param context
     * @return
     */
    public static DBHelper getInstance(Context context){
        if (dbHelper==null){
            dbHelper=new DBHelper(context);
        }
        return dbHelper;

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(SQL_DROP);
        db.execSQL(SQL_CREATE);
    }
}
ThreadDaoImpl.class

    public synchronized void updateThread(String url, int thread_id, int finished) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.execSQL(updateSQL, new Object[]{finished, thread_id,url});
        db.close();
    }

2、线程池使用

//创建线程池
public  static ExecutorService executorService=Executors.newCachedThreadPool();
//线程池使用
executorService.execute(downloadThread);
2.1 接口:ExecutorService
    Executors类提供四种线程池
newCachedThreadPool()//带缓存的线程池,线程开的很多的时候,当线程不使用了就被缓存起来,当系统需要时又从缓存的线程池中取出使用;大小没有限制是由系统支持的线程数决定
newFixedThreadPool(int)//固定数量的线程池
newScheduledThreadPool()//周期性定时去执行某些任务,线程数没有限制
newSingleThreadExecutor()//只有单个任务的线程池

代码 点击打开链接


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值