使用SwingWorker类优化耗时操作

编程 专栏收录该内容
¥29.90 ¥99.00
353篇文章

使用SwingWorker类优化耗时操作

在开发Java应用程序时,我们有时会遇到需要执行耗时操作的情况,比如进行网络请求、读取大量数据或进行复杂的计算。如果将这些操作直接放在主线程中执行,会导致用户界面无响应,用户体验变差。为了解决这个问题,Java提供了SwingWorker类,它可以帮助我们在后台线程中执行耗时操作,从而保持用户界面的流畅性。

SwingWorker类是javax.swing包中的一个抽象类,它提供了一个方便的方式来执行后台任务,并在任务执行完成后更新用户界面。下面我们将以一个示例来演示如何使用SwingWorker类来优化耗时操作。

首先,我们需要创建一个继承自SwingWorker类的子类,该子类将负责执行我们的耗时操作。假设我们要进行一个需要耗费较长时间的计算任务,计算结果将在计算完成后显示在用户界面上。我们可以定义一个名为CalculationWorker的类来执行这个任务。

import javax.swing.SwingWorker;

91、Java并发编程:并发集合与SwingWorker的应用 本文介绍了Java并发编程中的并发集合与SwingWorker的应用。并发集合如ConcurrentHashMap和ArrayBlockingQueue等,为多线程环境下的数据共享提供了高效且线程安全的解决方案。SwingWorker则用于Swing GUI应用中处理长时间计算任务,通过工作线程执行耗时操作并在事件调度线程更新界面,提高了应用的响应性和用户体验。文章通过斐波那契数列计算和埃拉托斯特尼筛法两个示例,详细展示了SwingWorker在处理并发任务和更新GUI方面的强大功能。 阅读详情

相关推荐

Swing线程的深入理解和SwingWorker基础知识介绍

Swing线程的深入理解和SwingWorker基础知识介绍

Java的Swing编程中使用SwingWorker线程模式及顶层容器

主要介绍了在Java的Swing编程中使用SwingWorker线程模式及顶层容器的方法,适用于客户端图形化界面软件的开发,需要的朋友可以参考下

WSL2+Ubuntu-22.04搭建PX4仿真环境:从零避坑到一键起飞

本文详细指导在Windows系统上通过WSL2和Ubuntu-22.04搭建PX4仿真开发环境的完整流程,涵盖环境配置、源码下载、依赖安装、Gazebo仿真及常见错误解决方案,帮助开发者从零避坑实现无人机一键起飞仿真。

k8s6orchestrator的博客 670

分子动力学模拟学习1-采用AmberTools21的MCPB.py构建金属蛋白的top文件

分子动力学模拟学习1-采用AmberTools21的MCPB.py构建金属蛋白的top文件

weixin_45011386的博客 3824

基于步科(Kinco HMI 2.5)的组态软件使用

本篇介绍Kinco HMI 2.5的组态软件使用,图标如下 目录   一、新建工程并配置连接 1.1 根据工程选择PLC与HMI型号 1.2 配置PLC连接与选项 二、组态画面编辑 2.1 打开画面窗口 2.2 编辑画面 2.3 组态变量与PLC程序变量连接 三、组态程序下载到HMI 3.1 连接 3.2 编译 3.3 下载 一、新建工程并配置连接 1.1 根据工...

ACanswer的专栏 1万+

用scons编译STM32F103工程

想用vscode来实现代码的编辑与调试代码,原先这个工程是用STM32CUBEIDE建立的,参照STM32CUBEIDE的编译过程,编写了下面的scons脚本,scons是初次了解,既然是python脚本,那么会什么就怎么写吧。 import os import sys import glob cross_compiler_prefix = 'arm-none-eabi-' CC = cross_compiler_prefix+'gcc' CXX = cross_compiler_prefix+'g+

cylinc的专栏 1623

SolidWorks+ADAMS双验证:你的机械臂力矩计算真的靠谱吗?

本文探讨了机械臂力矩计算中手工计算的局限性,并介绍了SolidWorks和ADAMS双验证方法的重要性。通过实际案例展示了动态工况下传统计算方法的误差,详细解析了SolidWorks精准质心捕捉和ADAMS动力学仿真的关键技术,帮助工程师构建计算-仿真-实测闭环验证流程,确保机械臂设计的可靠性和安全性。

grafana6viz的博客 228

傻白入门芯片设计,SystemVerilog Assertion(SVA)学习(二十一)

对SVA(SystemVerilogt Assertion)有了更深刻的认识,对经典的AveMC形式验证工具进行了介绍

qq_46675545的博客 8470

MFC Windows 程序设计[105]之彩色滚动条(附源码)

MFC是微软公司提供的一个类库(class libraries),用以减少应用程序开发人员的工作量。其中包含大量Windows句柄封装类和很多Windows的内建控件和组件的封装类。有很多初学MFC的小伙伴们都觉得MFC比较难学,看书吧,看了就忘了,网上的一些教程又是写的含糊不清,故而学习起来很吃力...... 故此,本专栏亲自研究,实践,由易到难,层层深入,将调试过程中所遭所遇进行详细讲解,注意事项进行一一列举,希望能够帮助到各位初学MFC的小伙伴,避免走弯路,费时费力。

hnjzfwy的博客 518

2025.05.30【转录组】|Ribo-seq数据流程详解(一 质量控制)

本文详细介绍了Ribo-seq数据的质控分析流程,重点讲解了使用fastp进行原始数据质控的关键步骤和参数设置。作者通过Snakemake自动化流程示例,展示了如何去除接头序列、过滤低质量reads、生成质控报告等操作。文章强调高质量的Ribo-seq数据对转录后调控和翻译动态研究的重要性,并提供了兼顾数据质量和下游分析需求的参数配置建议。该流程有助于研究人员规范高效地完成Ribo-seq数据质控,为后续分析提供可靠数据基础。

784

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: Java实现批量修改文件类型
下一篇: C&C++表达式语句实训:探索编程中的表达力
普通网友
博客等级 码龄3年 221粉丝 707原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值