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

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()//只有单个任务的线程池

代码 点击打开链接


猜你喜欢

转载自blog.csdn.net/u013359807/article/details/80389865