Java学习笔记(多线程)
- 学习说明
- 第二十九章 多线程
- 创建任务和线程
- Thread类
- 实例学习--闪烁文本
- GUI事件分发线程
- 实例学习--带音频的时钟
- 线程池
- 线程同步
- 利用加锁同步
- 线程间协作(线程间相互通信)
- 实例学习--生产者/消费者
- 阻塞队列
- 信号量
- 避免死锁
- 线程的状态
- 同步集合
- SwingWorker
- JProgressBar
学习说明
要点:
讲解了基本的创建线程、线程同步,线程阻塞队列,加锁,以及比较有趣的进度条
学习资料为:《Java语言程序设计》梁勇
第二十九章 多线程
创建任务和线程
任务类必须实现Runnable接口,即实现run方法
// 任务类,实现了Runnable接口和run方法
public class TaskClass implements Runnable {
@Override
public void run() {
System.out.println("The run is running!");
}
public TaskClass() {
System.out.println("我被创建了");
}
}
// 测试主类,创建线程
public class CreateThreadTest {
public static void main(String[] args) {
TaskClass task = new TaskClass();
Thread thread = new Thread(task); // Thread方法有重载
thread.start();
}
public CreateThreadTest() {
}
}
下面给出一些经典例子进行讲解
// 在没有设置优先级的时候,会造成线程争抢资源,打印结果并不十分美观
public class TaskThreadDemo {
public static void main(String[] args) {
Runnable printA = new PrintChar('a', 100);
Runnable printB = new PrintChar('b', 100);
Runnable print100 = new PrintNum(100);
Thread thread1 = new Thread(printA);
Thread thread2 = new Thread(printB);
Thread thread3 = new Thread(print100);
// 这个地方设置了优先级,就不会抢占了,但优先级只有这三种常量
// 设置了仍然会有抢占的可能性,只是大部分会按顺序,这也很奇怪呀,可能和静态类有关,我设置了静态成员属性,,经过测试发现并不是静态成员属性的问题
// 所以还是需要通过代码设定阻塞与睡眠来调整运行情况
// 可以手动设定在1-10之间
// thread1.setPriority(Thread.MAX_PRIORITY);
// thread2.setPriority(Thread.NORM_PRIORITY);
// thread3.setPriority(Thread.MIN_PRIORITY);
// thread1.setPriority(10);
// thread2.setPriority(5);
// thread3.setPriority(1);
thread1.start();
thread2.start();
thread3.start();
}
static class PrintChar implements Runnable {
private char charToPrint;
private int times;
public PrintChar(char ch, int times) {
this.charToPrint = ch;
this.times = times;
}
@Override
public void run() {
int count = 0;
for (int i = 0; i < times; i++) {
System.out.print(charToPrint + " ");
count++;
if(count % 10 == 0)
System.out.println();
}
System.out.println();
}
}
static class PrintNum implements Runnable {
private int lastNum;
public PrintNum(int num) {
this.lastNum = num;
}
@Override
public void run() {
int count = 0;
for (int i = 0; i < lastNum; i++) {
System.out.printf("%3d", i);
count++;
if(count % 10 == 0)
System.out.println();
}
System.out.println();
}
}
}
Thread类
Thread常用属性及方法:
构造函数
start
isAlive
setPriority
join
sleep
yield
interrupt
Thread类实现了Runnable接口,所以是可以直接继承Thread类,进行线程的创建,但不推荐,因为将任务和运行混合在一起不好
// 继承了Thread类
public class CustomThread extends Thread {
public CustomThread() {
System.out.println("CustomThread is created!");
}
public void run() {
System.out.println("The run is running!");
}
@Test
public void testCreateThread() {
// 看上去还蛮整洁的
CustomThread thread1 = new CustomThread();
thread1.start();
CustomThread thread2 = new CustomThread();
thread2.start();
}
}
Thread类还包含stop、suspend、resume方法,但这些方法有内在的不安全因素(我也不知道不安全在哪),所以这些方法就没用了
为了代替stop方法,可以通过给Thread变量赋值为空表明被停止
下面结合之前的打印字母、数字的例子继续讲解yield、sleep、join方法的功能
// 例子不好给呀,只需要了解这三个方法的最基本用法就好了
实例学习–闪烁文本
熟悉最基本的sleep函数的使用
public class FlashingText extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
private JLabel jLabelText = new JLabel("BBYH", JLabel.CENTER);
public FlashingText() {
jLabelText.setFont(new Font("Times New Roman", Font.BOLD, 30));
this.add(jLabelText);
new Thread(this).start();
}
@Override
public void run() {
while (true) {
if (jLabelText.getText() == null) {
jLabelText.setText("BBYH");
} else {
jLabelText.setText(null); // 注意这里,空字符串和null是不一样的
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JFrame frame = new FlashingText();
frame.setTitle("Flashing Text");
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
GUI事件分发线程
GUI事件处理和绘图代码在一个被称为事件分发线程的特殊线程中执行,由于大多Swing方法不是线程安全的,从多线程调用可能会发生冲突
public class EventDispatcherThreadDemo extends JFrame {
private static final long serialVersionUID = 1L;
public EventDispatcherThreadDemo() {
add(new JLabel("Hi, it runs from an event dispatch thread", JLabel.CENTER));
}
// 这个地方加个线程不是很懂,意义很大吗,得等以后才能知道了
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new EventDispatcherThreadDemo();
frame.setTitle("Event Dispatcher ThreadDemo");
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
实例学习–带音频的时钟
权当复习一下之前的知识好了,这边没有太多花里胡哨的,而且Applet在jdk9已经被废弃,预计要删掉
public class ClockWithAudio extends JFrame {
private static final long serialVersionUID = 1L;
protected AudioClip[] hourAudio = new AudioClip[12];
protected AudioClip[] minuteAudio = new AudioClip[60];
protected AudioClip amAaudio = Applet.newAudioClip(this.getClass().getResource("audio/am.au"));
protected AudioClip pmAaudio = Applet.newAudioClip(this.getClass().getResource("audio/pm.au"));
private StillClock clock = new StillClock();
private Timer timer = new Timer(1000, new TimerLieteber());
private JLabel jLabelDigitTime = new JLabel("", JLabel.CENTER);
public void init() {
for (int i = 0; i < hourAudio.length; i++) {
hourAudio[i] = Applet.newAudioClip(this.getClass().getResource("audio/hour" + i + ".au"));
}
for (int i = 0; i < minuteAudio.length; i++) {
minuteAudio[i] = Applet.newAudioClip(this.getClass().getResource("audio/minute" + i + ".au"));
}
this.add(clock, BorderLayout.CENTER);
this.add(jLabelDigitTime, BorderLayout.SOUTH);
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
}
class TimerLieteber implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
clock.setCurrentTime();
clock.repaint();
jLabelDigitTime.setText(clock.getHour() + ":" + clock.getMinute() + ":" + clock.getSecond());
if(clock.getSecond() == 0)
announceTime(clock.getHour(), clock.getMinute());
}
}
public void announceTime(int hour, int minute) {
hourAudio[hour % 12].play();
try {
Thread.sleep(1500);
minuteAudio[minute].play();
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(hour < 12)
amAaudio.play();
else
pmAaudio.play();
}
public ClockWithAudio() {
init();
start();
}
public static void main(String[] args) {
JFrame frame = new ClockWithAudio();
frame.setTitle("ClockWithAudio");
frame.setSize(700, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
线程池
线程每次自己创建太麻烦了,效率也不高,所以就一次创建多个,到时候一起用就好了,在线程池还有空线程没被占用就直接拿过来用,都被占用了则等待,单个线程被占用60秒都没有执行线程,则该资源占用被释放
Executor接口、ExecutorService接口(实现Executor接口)
Executors类提供创建Executor对象的静态方法
下面为创建线程池示例:
public class CreateExecutorDemo {
public static void main(String[] args) {
new CreateExecutorDemo();
}
public CreateExecutorDemo() {
// 创建最大线程数为3的线程池
ExecutorService executor = Executors.newFixedThreadPool(3);
// ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new PrintChar('a', 100));
executor.execute(new PrintChar('b', 100));
executor.execute(new PrintNum(100));
// 通知执行器关闭,不能接受新的任务,但现有的任务将继续执行
executor.shutdown();
}
class PrintChar implements Runnable {
private char charToPrint;
private int times;
public PrintChar(char ch, int times) {
this.charToPrint = ch;
this.times = times;
}
@Override
public void run() {
int count = 0;
for (int i = 0; i < times; i++) {
System.out.print(charToPrint + " ");
count++;
if(count % 10 == 0)
System.out.println();
}
System.out.println();
}
}
class PrintNum implements Runnable {
private int lastNum;
public PrintNum(int num) {
this.lastNum = num;
}
@Override
public void run() {
int count = 0;
for (int i = 0; i < lastNum; i++) {
System.out.printf("%3d", i);
count++;
if(count % 10 == 0)
System.out.println();
}
System.out.println();
}
}
}
线程同步
一个共享资源被多个线程同时访问,可能会遭到破坏,下面进行演示:
public class AccountWithoutSync {
private static Account account = new Account();
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
// 创建100个线程进行转账操作,结果最终金额不对了
for (int i = 0; i < 100; i++) {
executor.execute(new AddApennyTask());
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println(account.getBalance());
}
private static class AddApennyTask implements Runnable {
@Override
public void run() {
account.deposit(1);
}
}
private static class Account {
private int balance = 0;
public int getBalance() {
return balance;
}
public void deposit(int amount) {
int newBalance = balance + amount;
// 当休眠时间较长时,结果则会稳定在1,休眠时间短则会不为1
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
balance = newBalance;
}
}
}
竞争状态,线程不安全
引入synchronized关键字,来保证线程安全性(实行同步,保证每次只有一个线程可以访问资源),通过加锁实现的
// 对方法,静态方法,静态方法是对类加锁,普通实例方法则对对象加锁
// 对下面的转账方法进行加锁同步,则结果稳定在100了
public synchronized void deposit(int amount) {
int newBalance = balance + amount;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
balance = newBalance;
}
同步语句(对任何一些语句块加锁,则不仅对于方法进行加锁)
// 这里对要进行访问的参数 account 进行加锁,实现同步
private static class AddApennyTask implements Runnable {
@Override
public void run() {
// account.deposit(1);
synchronized (account) {
account.deposit(1);
}
}
}
利用加锁同步
显示的加锁:Lock接口
Lock接口和它的实现类ReentrantLock类:
Lock的常用方法:
lock、unlock、newCondition
ReentrantLock类的常用方法:
构造函数
ReentrantLock(fair:boolean):设置为true,则选择等待时间最长的获得锁
示例如下:
// 基本上和上面的例子没啥区别,只在转账的时候进行了加锁
public class AccountWithSyncUsingLock {
private static Account account = new Account();
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
executor.execute(new AddApennyTask());
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println(account.getBalance());
}
private static class AddApennyTask implements Runnable {
@Override
public void run() {
account.deposit(1);
}
}
private static class Account {
// 创建(声明)锁对象
private static Lock lock = new ReentrantLock();
private int balance = 0;
public int getBalance() {
return balance;
}
// 这个方法进行了加锁,很像操作系统的互斥访问
public void deposit(int amount) {
lock.lock();
try {
int newBalance = balance + amount;
Thread.sleep(1);
balance = newBalance;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
线程间协作(线程间相互通信)
在C语言里面,线程间通信的方式一般有以下几种:
共享存储区
Socket
管道
消息队列
在Java里面要讲 Condition接口,常用方法如下:
await(让线程等待,知道某个条件才自动解锁)
signal(唤醒线程)
signalAll(唤醒所有线程)
下面以存款、取款为例,演示这三个常用方法:
两个线程,一个存款,一个取款
取款金额大于当前余额,则需要等待
存款则不管什么时候都能进行,且存款过后自动让取款金额不够的线程自动再尝试一次
public class ThreadCoopearation {
private static Account account = new Account();
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new DepositTask());
executor.execute(new WithdrawTask());
executor.shutdown();
System.out.println("Thread 1ttThread 2ttBalance");
}
public static class DepositTask implements Runnable {
@Override
public void run() {
try {
while (true) {
account.deposit((int)(Math.random() * 10) + 1);
Thread.sleep(5000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static class WithdrawTask implements Runnable {
@Override
public void run() {
while (true) {
account.withdraw((int)(Math.random() * 10) + 1);
}
}
}
private static class Account {
private static Lock lock = new ReentrantLock();
// 获得一个锁
private static Condition newDeposit = lock.newCondition();
private int balance = 0;
public int getBalance() {
return balance;
}
public void withdraw(int amount) {
lock.lock();
try {
// 进行判断,余额不够则等待,while换成if则会导致问题,出现余额为负数的情况
while (balance < amount) {
System.out.println("ttWait for amount deposit");
newDeposit.await();
}
balance -= amount;
System.out.println("tttWithdraw " + amount + "tt" + getBalance());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void deposit(int amount) {
lock.lock();
try {
balance += amount;
System.out.println("Deposit " + amount + "ttttt" + getBalance());
// 唤醒所有取款操作
newDeposit.signalAll();
} finally {
lock.unlock();
}
}
}
}
Java的内置监视器:
Java5之前锁和条件还没出现,则是采用监视器进行线程通信
wait、notify、notifyAll三个方法
实例学习–生产者/消费者
采用向缓冲区添加整数和删除整数为例,进行生产者与消费者的演示
public class ConsumerProducer {
private static Buffer buffer = new Buffer();
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new ProducerTask());
executor.execute(new ConsumerTask());
executor.shutdown();
}
private static class ProducerTask implements Runnable {
@Override
public void run() {
try {
int i = 1;
while (true) {
System.out.println("Produce writes " + i);
buffer.write(i++);
Thread.sleep((int)(Math.random() * 1000));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class ConsumerTask implements Runnable {
@Override
public void run() {
try {
while (true) {
System.out.println("ttProduce reads " + buffer.read());
Thread.sleep((int)(Math.random() * 1000));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class Buffer {
private static final int CAPACITY = 1;
LinkedList queue = new LinkedList();
private static Lock lock = new ReentrantLock();
private static Condition notEmpty = lock.newCondition();
private static Condition notFull = lock.newCondition();
// 写入的时候进行判断,已经写入了则等待,同样需要采用while,则不是if
public void write(int value) {
lock.lock();
try {
while (queue.size() == CAPACITY) {
System.out.println("Wait for notFull condition");
notFull.await();
}
queue.offer(value);
notEmpty.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
// 读的时候,需要判断是不是为空
@SuppressWarnings("finally")
public int read() {
int value = 0;
lock.lock();
try {
while (queue.isEmpty()) {
System.out.println("ttWait for notEmpty condition");
notEmpty.await();
}
value = queue.remove();
notFull.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
return value;
}
}
}
}
阻塞队列
Collection->Queue->BlockingQueue
BlockingQueue的常用方法:
put、take
Java支持三个具体的阻塞队列:
ArrayBlockingQueue
LinkedBlockingQueue
PriorityBlockingQueue
下面采用ArrayBlockingQueue简化上面的生产者/消费者问题
// 因为同步部分在 ArrayBlockingQueue 里面它自己实现了,就不用手写同步了,简化了许多
public class ConsumerProducerUsingBlockingQueue {
private static ArrayBlockingQueue buffer = new ArrayBlockingQueue(2);
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new ProducerTask());
executor.execute(new ConsumerTask());
executor.shutdown();
}
private static class ProducerTask implements Runnable {
@Override
public void run() {
try {
int i = 1;
while (true) {
System.out.println("Produce writes " + i);
buffer.put(i++);
Thread.sleep((int)(Math.random() * 1000));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class ConsumerTask implements Runnable {
@Override
public void run() {
try {
while (true) {
System.out.println("ttProduce reads " + buffer.take());
Thread.sleep((int)(Math.random() * 1000));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
信号量
Semaphore类,常用方法:
构造函数
acquire
release
下面对原来的转账示例进行修改,保证同一时间只有一个线程能够访问deposit方法
public class AccountWithSemaphore {
// 这里创建信号量为一,一次只能用一个访问
private static Semaphore semaphore = new Semaphore(1);
private int balance = 0;
public int getBalance() {
return balance;
}
public void deposit(int amount) {
try {
semaphore.acquire();
Thread.sleep(1);
balance += amount;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
private static AccountWithSemaphore account = new AccountWithSemaphore();
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
executor.execute(new AddApennyTask());
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println(account.getBalance());
}
private static class AddApennyTask implements Runnable {
@Override
public void run() {
account.deposit(1);
}
}
}
避免死锁
感觉回到了操作系统,需要采用按序申请资源的方式进行避免死锁
死锁的四个必要条件:
互斥条件
请求和保持
不剥夺
环路等待
public class DeadLockDemo {
static Data data1 = new Data();
static Data data2 = new Data();
static int count = 0;
public static void main(String[] args) {
System.out.println("result");
ExecutorService executor = Executors.newCachedThreadPool();
// 创建100个线程进行转账操作,结果最终金额不对了
for (int i = 0; i < 100; i++) {
executor.execute(new Demo1());
executor.execute(new Demo2());
}
executor.shutdown();
}
static class Data {
}
private static class Demo1 implements Runnable {
@Override
public void run() {
// 这里申请两个资源,下面同样申请两个资源,有一定的可能性造成冲突(因为实践得出,不是每次都会发生阻塞)
synchronized (data1) {
synchronized (data2) {
count++;
System.out.println(count);
}
}
}
}
private static class Demo2 implements Runnable {
@Override
public void run() {
// 都已经这样申请了,结果仍然不是每次都阻塞,我不是很理解
synchronized (data2) {
synchronized (data1) {
count++;
System.out.println(count);
}
}
}
}
}
线程的状态
五种基本状态:新建、就绪、运行、阻塞、结束
isAlive判断,线程处于就绪、运行、阻塞则返回true,处于新建还未就绪和结束则返回false
同步集合
Java的集合框架中的类不是线程安全的,所以需要转化,Collections类中提供了六个静态方法来转化:
synchronizedCollections
synchronizedList
synchronizedMap
synchronizedSet
synchronizedSortedMap
synchronizedSortedList
但迭代器具有快速失败特性,所以需要每次遍历时都创建一个迭代器
// 演示不出来线程不安全的情况,只要添加了 synchronized 关键字,还是达到了同步
public class CollectionsSyncTest {
private static List list = new ArrayList();
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
executor.execute(new Demo1());
}
executor.shutdown();
// 这一句不能少,不然后面的结果被提前输出,就演示不出来了
while (!executor.isTerminated()) {
}
System.out.println(list.size());
System.out.println(list);
}
// 只有一个线程时添加了 synchronized 关键字之后是达到了同步的
// 没添加时,是会有一定概率出现结果错误的
public synchronized static void addList(int value) {
list.add(value);
}
static class Demo1 implements Runnable {
@Override
public void run() {
addList(1);
}
}
}
// 与一般的变量,加上 synchronized 修饰,是可以达到同步效果的,没有啥差别
public class IntegerVariableSyncTest {
private static int count = 0;
@Test
public void testIntegerSync() {
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
executor.execute(new Demo1());
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println(count);
}
static class Demo1 implements Runnable {
@Override
public void run() {
add();
}
}
// 一定要放在run函数之外的函数上,且内部要有延时,不然就算不加同步,也基本没有出现错误,且要有中间变量
public synchronized static void add() {
int newCount = count + 1;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
count = newCount;
}
}
SwingWorker
相较于前面的Swing GUI的事件分发线程,这里的SWingWorker是实现了Runnable的一个抽象类
这个类可以用于运行比较费事的任务并更新GUI
下面采用寻找素数作为演示:
// 主要说明为了一点,费时的操作在SwingWorker里面执行
public class SwingWorkerDemo extends JFrame {
private static final long serialVersionUID = 1L;
private JButton jbtnComputeWithSwingWorker = new JButton("Compute");
private JTextField jtfLimit1 = new JTextField(8);
private JTextField jtfResult1 = new JTextField(6);
private JButton jbtnCompute = new JButton("Compute");
private JTextField jtfLimit2 = new JTextField(8);
private JTextField jtfResult2 = new JTextField(6);
public SwingWorkerDemo() {
JPanel panel1 = new JPanel(new GridLayout(2, 1));
panel1.setBorder(BorderFactory.createTitledBorder("Using SwingWorker"));
JPanel panel11 = new JPanel();
panel11.add(new JLabel("The number of prime numbers <= "));
panel11.add(jtfLimit1);
panel11.add(new JLabel("is"));
panel11.add(jtfResult1);
JPanel panel12 = new JPanel();
panel12.add(jbtnComputeWithSwingWorker);
panel1.add(panel11);
panel1.add(panel12);
JPanel panel2 = new JPanel(new GridLayout(2, 1));
panel1.setBorder(BorderFactory.createTitledBorder("Without Using SwingWorker"));
JPanel panel21 = new JPanel();
panel11.add(new JLabel("The number of prime numbers <= "));
panel11.add(jtfLimit2);
panel11.add(new JLabel("is"));
panel11.add(jtfResult2);
JPanel panel22 = new JPanel();
panel12.add(jbtnCompute);
panel2.add(panel21);
panel2.add(panel22);
setLayout(new GridLayout(1, 2));
add(panel1);
add(panel2);
jbtnComputeWithSwingWorker.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new ComputePrime(Integer.parseInt(jtfLimit1.getText()), jtfResult1).execute();
}
});
jbtnCompute.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int count = ComputePrime.getNumberOfPrimes(Integer.parseInt(jtfLimit2.getText()));
jtfResult2.setText(count + "");
}
});
}
// SWingWorker被继承
static class ComputePrime extends SwingWorker {
private int limit;
private JTextField result;
public ComputePrime(int limit, JTextField result) {
this.limit = limit;
this.result = result;
}
@Override
protected Integer doInBackground() throws Exception {
return getNumberOfPrimes(limit);
}
protected void done() {
try {
result.setText(get().toString());
} catch (Exception e) {
result.setText(e.getMessage());
}
}
public static int getNumberOfPrimes(int limit) {
int count = 0;
int number = 2;
while (number < limit) {
if(isPrime(number))
count++;
number++;
}
return count;
}
private static boolean isPrime(int number) {
for (int i = 2; i <= number / 2; i++) {
if(number % i == 0)
return false;
}
return true;
}
}
public static void main(String[] args) {
JFrame frame = new SwingWorkerDemo();
frame.setTitle("SwingWorkerDemo");
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
JProgressBar
显示进度条,直接上示例:
四个常用属性:(都有get、set方法的)
orientation(方向)、minimum、value、maximum
public class ProgressBarDemo extends JFrame {
private static final long serialVersionUID = 1L;
private JProgressBar jpb = new JProgressBar();
private static JTextArea jtaResult = new JTextArea();
private JTextField jtfPrimeCount = new JTextField(8);
private JButton jbtnDisplayPrime = new JButton("Display Prime");
public static void main(String[] args) {
JFrame frame = new ProgressBarDemo();
frame.setTitle("ProgressBarDemo");
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public ProgressBarDemo() {
jpb.setStringPainted(true);
jpb.setValue(0);
jpb.setMaximum(100);
jtaResult.setWrapStyleWord(true);
jtaResult.setLineWrap(true);
JPanel panel = new JPanel();
panel.add(new JLabel("Enter the prime number count"));
panel.add(jtfPrimeCount);
panel.add(jbtnDisplayPrime);
add(jpb, BorderLayout.NORTH);
add(new JScrollPane(jtaResult), BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
// 这一整个事件可不简单的
jbtnDisplayPrime.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ComputePrime task = new ComputePrime(Integer.parseInt(jtfPrimeCount.getText()), jtaResult);
task.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
if("progress".equals(e.getPropertyName())) {
jpb.setValue((Integer)e.getNewValue());
}
}
});
task.execute(); // 这里需要开始执行
}
});
}
static class ComputePrime extends SwingWorker {
private int count;
private JTextArea result;
public ComputePrime(int count, JTextArea result) {
this.count = count;
this.result = result;
}
@Override
protected Integer doInBackground() {
publishPrimeNumbers(count);
return 0;
}
protected void process(List list) {
for (Integer integer : list) {
result.append(integer + " ");
}
}
// 这里设置值还是蛮巧妙的
private void publishPrimeNumbers(int n) {
int count = 0;
int number = 2;
while (count <= n) {
if(isPrime(number)) {
count++;
setProgress(100 * count / n);
publish(number);
}
number++;
}
}
private static boolean isPrime(int number) {
for (int i = 2; i <= number / 2; i++) {
if(number % i == 0)
return false;
}
return true;
}
}
}