Preface:
1 线程和进程的区别联系
进程:应用程序的执行实例
线程:CPU调度和分派的基本单位
区别
联系
2 并发 交替占用 并行
3 创建线程的方式
1)extends java.lang.Thread (class)
2)implements java.lang.Runnable (interface)
4 线程状态5 state
5 线程调度的函数
multithreaded
可以同时运行一个以上线程的程序称为multithreaded
多进程与多线程的一些区别:
每个进程拥有自己的一套变量,线程共享数据
共享变量使线程之间的通信比进程之间的通信更有效、更容易
在有的操作系统中,线程相较于进程更“轻量级”,创建、撤销一个线程比启动新进程的开销要小得多
线程:
P638
java.lang.Thread 1.0
static void sleep(long millis)休眠给定的毫秒数
参数:millis 休眠的毫秒数
使用线程给其他任务提供机会
AWT的event dispatch thread
在一个单独的线程中执行一个任务的简单过程
1)将任务代码移到实现了Runnable接口的类的run方法中
public interface Runnable{
void run();
}
可以如下所示实现一个类:
class MyRunnable implements Runnable{
public void run(){
task code
}
}
2)创建一个类对象
Runnable r=new MyRunnable();
3)由Runnable创建一个Thread对象:
Thread t=new Thread(r);
4)启动线程
t.start();
想将球代码放在一个独立的线程中,只要实现一个类BallRunnable,然后将动画放在run中
class BallRunnable implements Runnable{
...
public void run(){
try{
for(int i=1;i<=STEPS;i++){
ball.move(component.getBounds());
component.repaint();
Thread.sleep(DELAY);
}
}
catch(InterruptedException)
{
}
}
...
}
此外,需要捕获sleep方法可能抛出的异常InterruptedException
一般情况下,线程在中断时被终止。因此当发生InterruptedException时,run方法将结束执行
无论何时点击Start按钮,addBall方法都将启动一个新线程
Ball b=new Ball();
panel.add(b);
Runnable r=new BallRunnable(b,panel);
Thread t=new Thread(r);
t.start();
tips:也可以通过构建一个Thread类的子类定义一个线程
class MyThread extends Thread{
public void run(){
task code
}
}
然后,构建一个子类的对象,并调用start方法。但是,应该从运行机制上减少需要并行的任务数量,因此这种方法已不再推荐。
warning:不要调用Thread类或Runnable对象的run方法。直接调用run方法,指挥执行同一个线程中的任务,儿不会启动新线程。应调用Thread.start方法。这个方法将创建一个执行run方法的新线程
bounceThread/BounceThread.java
P645
package bounceThread;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**Shows animated bouncing balls.
*/
public class BounceThread{
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
JFrame frame=new BounceFrame();
frame.setTile("BounceThread");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**A runnable that animates a bouncing ball.
*/
class BallRunnable implements Runnable{
private Ball ball;
private Component component;
public static final int STEPS=1000;
public static final int DELAY=5;
/**Constructs the runnable.
*/
public BallRunnable(Ball aBall,Component aComponent){
ball=aBall;
component=aComponent;
}
public void run(){
try{
for(int i=1;i<=STEPS;i++){
ball.move(component.getBounds());
component.repaint();
Thread.sleep(DELAY);
}
}
catch(InterruptedException e){
}
}
}
/**The frame with panel and buttons.
*/
class BounceFrame extends JFrame{
private BallComponent comp;
/**Constructs the frame with the compon