进程与线程
概念
互斥 资源有限,需抢占
同步 协作完成一项任务,有先后顺序
java线程初探
java对线程的支持
Thread
类和Runnable
接口,以及共同的run()
方法。Thread类
join()
使当前运行线程等待调用线程的终止,再继续运行yield()
使当前运行线程释放处理器资源
停止线程的错误方法 1.stop()2.interrupt()
使用退出标志(volatile bool keepRunning
)停止线程循环Thread和Runnable示例
Thread和Runnable各自每运行10次暂停1s,交替运行。一个.java文件可有多个类(不包括内部类),但只能有一个public类。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51public class Actor extends Thread {
public void run(){
System.out.println(getName()+"是一个演员!");
int count = 0;
boolean keepRunning = true;
while(keepRunning){
System.out.println(getName()+"登台演出:"+ (++count));
if(count == 100){
keepRunning = false;
}
if(count%10== 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(getName()+"的演出结束了!");
}
public static void main(String[] args){
Thread actor = new Actor();
actor.setName("Mr. Thread");
actor.start();
Thread actressThread = new Thread(new Actress(),"Ms. Runnable");
actressThread.start();
}
}
class Actress implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName()+"是一个演员!");
int count = 0;
boolean keepRunning = true;
while(keepRunning){
System.out.println(Thread.currentThread().getName()+"登台演出:"+ (++count));
if(count == 100){
keepRunning = false;
}
if(count%10== 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(Thread.currentThread().getName()+"的演出结束了!");
}
}总结一下:
线程的生命周期
阻塞事件:如sleep(),wait(),join()
方法被调用java守护线程
java线程分两类:
1.用户线程
2.守护线程 一旦所有用户线程都结束了,守护线程也就结束了jstack生成线程快照