使用的教材是java核心技术卷1,我将跟着这本书的章节同时配合视频资源来进行学习基础java知识。
day089 并发(一)(什么是线程:使用线程给其他任务提供机会)
大家很熟悉操作系统中的多任务(multitasking):在同一刻运行多个程序的能力。例如,在编辑或下载邮件的同时可以打印文件。今天,人们很可能有单台拥有多个CPU的计算机,但是,并发执行的进程数目并不是由CPU数目制约的。操作系统将CPU的时间片分配给每一个进程,给人并行处理的感觉。
多线程程序在较低的层次上扩展了多任务的概念:一个程序同时执行多个任务。通常,每一个任务称为一个线程(thread),它是线程控制的简称。可以同时运行一个以上线程的程序称为多线程程序(multithreaded)。
那么,多进程与多线程有哪些区别呢?本质的区别在于每个进程拥有自己的一整套变量,而线程则共享数据。这听起来似乎有些风险,的确也是这样,在本章稍后将可以看到这个问题。然而,共享变量使线程之间的通信比进程之间的通信更有效、更容易。此外,在有些操作系统中,与进程相比较,线程更“轻量级”,创建、撤销一个线程比启动新进程的开销要小得多。
在实际应用中,多线程非常有用。例如,一个浏览器可以同时下载几幅图片。一个Web服务器需要同时处理几个并发的请求。图形用户界面(GUI)程序用一个独立的线程从宿主操作环境中收集用户界面的事件。
什么是线程
这里从察看一个没有使用多线程的程序开始。用户很难让它执行多个任务。在对其进行剖析之后,将展示让这个程序运行几个彼此独立的多个线程是很容易的。这个程序采用不断地移动位置的方式实现球跳动的动画效果,如果发现球碰到墙壁,将进行重绘。
当点击Start按钮时,程序将从屏幕的左上角弹出一个球,这个球便开始弹跳。Start按钮的处理程序将调用addBall方法。这个方法循环运行1000次move。每调用一次move,球就会移动一点,当碰到墙壁时,球将调整方向,并重新绘制面板。
Ball ball = newBall();
panel.add(ball);
for (int i = 1;i <= STEPS;i++)
{
ball.move(panel.getBounds());
panel.paint(panel.getCraphics());
Thread.sleep(DELAY);
}
调用Threadsleep不会创建一个新线程,sleep是Thread类的静态方法,用于暂停当前线程的活动。
sleep方法可以抛出一个IntermptedException异常。稍后将讨论这个异常以及对它的处理。现在,只是在发生异常时简单地终止弹跳。
如果运行这个程序,球就会自如地来回弹跳,但是,这个程序完全控制了整个应用程序。如果你在球完成1000次弹跳之前已经感到厌倦了,并点击Close按钮会发现球仍然还在弹跳。在球自己结束弹跳之前无法与程序进行交互。
显然,这个程序的性能相当糟糕。人们肯定不愿意让程序用这种方式完成一个非常耗时的工作。毕竟,当通过网络连接读取数据时,阻塞其他任务是经常发生的,有时确实想要中断读取操作。例如,假设下载一幅大图片。当看到一部分图片后,决定不需要或不想再看剩余的部分了,此时,肯定希望能够点击Stop按钮或Back按钮中断下载操作。下面是程序:
/**
*@author zzehao
*/
import java.awt.*;
import java.util.*;
import javax.swing.*;
//The component that draws the balls.
public class BallComponent extends JPanel
{
private static final int DEFAULT_WIDTH = 450;
private static final int DEFAULT_HEIGHT = 350;
private java.util.List<Ball> balls = new ArrayList<>();
//Add a ball to the component.
public void add(Ball b)
{
balls.add(b);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);//erase background
Graphics2D g2 = (Graphics2D) g;
for(Ball b : balls)
{
g2.fill(b.getShape());
}
}
public Dimension getPreferredSize()
{
return new Dimension(DEFAULT_WIDTH,DEFAULT_HEIGHT);
}
}
/**
*@author zzehao
*/
import java.awt.geom.*;
//A ball that moves and bounces off the edges of a rectangle
public class Ball
{
private static final int XSIZE = 15;
private static final int YSIZE = 15;
private double x = 0;
private double y = 0;
private double dx = 1;
private double dy = 1;
//Moves the ball to the next position, reversing direction if it hits one of the edges
public void move(Rectangle2D bounds)
{
x += dx;
y += dy;
if (x < bounds.getMinX())
{
x = bounds.getMinX();
dx = -dx;
}
if (x + XSIZE >= bounds.getMaxX())
{
x = bounds.getMaxX() - XSIZE;
dx =- dx;
}
if (y < bounds.getMinY())
{
y = bounds.getMinY();
dy= -dy;
}
if (y + YSIZE >= bounds.getMaxY())
{
y = bounds.getMaxY() - YSIZE;
dy = -dy;
}
}
//Gets the shape of the ball at its current position.
public Ellipse2D getShape()
{
return new Ellipse2D.Double(x,y,XSIZE, YSIZE);
}
}
/**
*@author zzehao
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Bounce
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new BounceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
//The frame with ball component and buttons.
class BounceFrame extends JFrame
{
private BallComponent comp;
public static final int STEPS = 1000;
public static final int DELAY = 3;
//Constructs the frame with the component for showing the bouncing ball and Start and Close buttons
public BounceFrame()
{
setTitle("Bounce");
comp = new BallComponent();
add(comp, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel, "Start", event -> addBall());
addButton(buttonPanel, "Close", event -> System.exit(0));
add(buttonPanel, BorderLayout.SOUTH);
pack();
}
//Adds a button to a container.
public void addButton(Container c, String title, ActionListener listener)
{
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
}
//Adds a bouncing ball to the panel and makes it bounce 1,000 times.
public void addBall()
{
try
{
Ball ball = new Ball();
comp.add(ball);
for (int i = 1; i <= STEPS; i++)
{
ball.move(comp.getBounds());
comp.paint(comp.getGraphics());
Thread.sleep(DELAY);
}
}
catch (InterruptedException e)
{
}
}
}
运行的结果:
1.使用线程给其他任务提供机会
可以将移动球的代码放置在一个独立的线程中,运行这段代码可以提高弹跳球的响应能力。实际上,可以发起多个球,每个球都在自己的线程中运行。另外,AWT的事件分派线程(eventdispatchthread)将一直地并行运行,以处理用户界面的事件。由于每个线程都有机会得以运行,所以在球弹跳期间,当用户点击Close按钮时,事件调度线程将有机会关注到这个事件,并处理“关闭”这一动作。
这里用球弹跳代码作为示例,让大家对并发处理有一个视觉印象。通常,人们总会提防长时间的计算。这个计算很可能是某个大框架的一个组成部分,例如,GUI或web框架。无论何时框架调用自身的方法都会很快地返回一个异常。如果需要执行一个比较耗时的任务,应当并发地运行任务。
下面是在一个单独的线程中执行一个任务的简单过程:
1)将任务代码移到实现了Runnable接口的类的run方法中。这个接口非常简单,只有一个方法:
public interface Runnable
{
void run();
}
由于 Runnable是一个函数式接口,可以用 lambda表达式建立一个实例:Runnable r = 0 -> { task code};
2)由Runnable创建一个Thread对象:Threadt=newThread(r);
3)启动线程:t.start();
要想将弹跳球代码放在一个独立的线程中,只需要实现一个类BallRunnable,然后,将动画代码放在nm方法中,如同下面这段代码:
Runnable r = () -> {
try
{
for (int i = 1; i <= STEPS; i++)
{
ball.move(comp.getBounds());
comp.repaint();
Thread.sleep(DELAY);
}
}
catch (InterruptedException e)
{
}
};
Thread t = new Thread(r);
t.start();
同样地,需要捕获sleep方法可能抛出的异常InterruptedException。在一般情况下,线程在中断时被终止。因此,当发生InterruptedException异常时,run方法将结束执行。无论何时点击Start按钮,球会移人一个新线程。下面是程序:
/**
*@author zzehao
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BounceThread
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
JFrame frame = new BounceFrame();
frame.setTitle("BounceThread");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
//The frame with panel and buttons.
class BounceFrame extends JFrame
{
private BallComponent comp;
public static final int STEPS = 1000;
public static final int DELAY = 5;
//Constructs the frame with the component for showing the bouncing ball and Start and Close buttons
public BounceFrame()
{
comp = new BallComponent();
add(comp, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel, "Start", event -> addBall());
addButton(buttonPanel, "Close", event -> System.exit(0));
add(buttonPanel, BorderLayout.SOUTH);
pack();
}
//Adds a button to a container.
public void addButton(Container c, String title, ActionListener listener)
{
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
}
//Adds a bouncing ball to the canvas and starts a thread to make it bounce
public void addBall()
{
Ball ball = new Ball();
comp.add(ball);
Runnable r = () -> {
try
{
for (int i = 1; i <= STEPS; i++)
{
ball.move(comp.getBounds());
comp.repaint();
Thread.sleep(DELAY);
}
}
catch (InterruptedException e)
{
}
};
Thread t = new Thread(r);
t.start();
}
}
运行的结果:(点击close就可退出)
不要调用Thread类或Runnable对象的run方法。直接调用run方法,只会执行同一个线程中的任务,而不会启动新线程。应该调用Thread.start方法。这个方法将创建一个执行ran方法的新线程。