zoukankan      html  css  js  c++  java
  • Java开发桌面程序学习(13)——Javafx多线程 下载功能

    普通使用

    Task<Void> task = new Task<Void>() {
    	@Override
    	protected void succeeded() {
    		super.succeeded();
    		//当call方法里面的操作完成,回调
    	}
    	
    	//还可以自定义一些方法,之后可以在call等方法调用
    
    	@Override
    	protected Void call() throws Exception {
    		//后台操作
    		return null;
    	}
    
    };
    new Thread(task).start();//启动线程
    

    进度条更新

    Task<Void> task = new Task<Void>() {
    	@Override
    	protected void succeeded() {
    		super.succeeded();
    		//当call方法里面的操作完成,回调
    	}
    	
    	//还可以自定义一些方法,之后可以在call等方法调用
    
    	@Override
    	protected Void call() throws Exception {
    		//模拟一个下载操作
    		for(int i=0;i<100;i++){
    			Thread.sleep(100);
    			//第一个参数是已完成,第二个参数则是全部,会自动计算
    			updata(i,100);
    		}
    		return null;
    	}
    };
    ProgressBar bar = new ProgressBar();
    bar.progressProperty().bind(task.progressProperty());
    //这里可以选择在一个按钮的点击事件中开启线程
    new Thread(task).start();
    

    暂停/继续功能实现

    思路,在controller中,存在一个boolean变量,用来判断当前是否已暂停,点击暂停按钮,会修改此boolean变量,默认为fasle
    之后,在线程里面实现一个while循环,每次通过之前的boolean变量来确定是否执行

    Task<Void> task = new Task<Void>() {
    	@Override
    	protected Void call() throws Exception {
    		int i=0;
    		while (i<100) {
    			//不是暂停,执行
    			if (!isPause) {
    				updateProgress(i, 100);
    				i++;
    			}else{
    				Thread.sleep(10);//这里如果没有,线程暂停之后就无法继续执行了
    			}
    		}
    		return null;
    	}
    };
    
  • 相关阅读:
    微软企业库Enterprise Library学习笔记一
    ASP.net的地址重写(URLRewriter)实现原理及代码示例
    Naive Bayes text classification
    [转]select、poll、epoll的比较
    linux 异步file I/O操作示例
    [转]Linux动态库(.so)搜索路径
    [转]python urllib2
    What is Third party cookie definition
    linux 相关工具
    关于最大熵模型
  • 原文地址:https://www.cnblogs.com/stars-one/p/11264196.html
Copyright © 2011-2022 走看看