什么是線程
線程是進(jìn)程的一個實(shí)體冷离,是CPU調(diào)度和分派的基本單位昙衅,它是比進(jìn)程更小的能獨(dú)立運(yùn)行的基本單位愁憔。
什么是多線程
多線程指在單個程序中可以同時運(yùn)行多個不同的線程執(zhí)行不同的任務(wù)抹锄。
創(chuàng)建多線程的3種方式
Thread焰手、Runnable糟描、Callable
1、繼承Thread類實(shí)現(xiàn)多線程
Thread thread = new Thread() {
@Override
public void run() {
super.run();
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1:" + Thread.currentThread().getName());
System.out.println("2:" + this.getName());
}
}
};
thread.start();
2书妻、實(shí)現(xiàn)Runnable接口方式實(shí)現(xiàn)多線程
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("3:" + Thread.currentThread().getName());
}
}
});
thread1.start();
3船响、Callable接口創(chuàng)建線程
public class CallableTest {
public static void main(String[] args) {
System.out.println("當(dāng)前線程是:" + Thread.currentThread());
Callable myCallable = new Callable() {
@Override
public Integer call() throws Exception {
int i = 0;
for (; i < 10; i++) {
}
//當(dāng)前線程
System.out.println("當(dāng)前線程是:" + Thread.currentThread()
+ ":" + i);
return i;
}
};
FutureTask<Integer> fu = new FutureTask<Integer>(myCallable);
Thread th = new Thread(fu, "callable thread");
th.start();
//得到返回值
try {
System.out.println("返回值是:" + fu.get());
} catch (Exception e) {
e.printStackTrace();
}
}
}
當(dāng)前線程是:Thread[main,5,main]
當(dāng)前線程是:Thread[callable thread,5,main]:10
返回值是:10
總結(jié)
實(shí)現(xiàn)Runnable接口相比繼承Thread類有如下優(yōu)勢:
可以避免由于Java的單繼承特性而帶來的局限;
增強(qiáng)程序的健壯性,代碼能夠被多個線程共享见间,代碼與數(shù)據(jù)是獨(dú)立的聊闯;
適合多個相同程序代碼的線程區(qū)處理同一資源的情況。
實(shí)現(xiàn)Runnable接口和實(shí)現(xiàn)Callable接口的區(qū)別:
Runnable是自從java1.1就有了缤剧,而Callable是1.5之后才加上去的
Callable規(guī)定的方法是call(),Runnable規(guī)定的方法是run()
Callable的任務(wù)執(zhí)行后可返回值馅袁,而Runnable的任務(wù)是不能返回值(是void)
call方法可以拋出異常,run方法不可以
運(yùn)行Callable任務(wù)可以拿到一個Future對象荒辕,表示異步計算的結(jié)果汗销。它提供了檢查計算是否完成的方法,以等待計算的完成抵窒,并檢索計算的結(jié)果弛针。通過Future對象可以了解任務(wù)執(zhí)行情況,可取消任務(wù)的執(zhí)行李皇,還可獲取執(zhí)行結(jié)果削茁。
加入線程池運(yùn)行,Runnable使用ExecutorService的execute方法掉房,Callable使用submit方法茧跋。
線程的生命周期與狀態(tài)
狀態(tài)名稱 | 說明 |
---|---|
NEW | 初始狀態(tài),線程被構(gòu)建卓囚,但是還沒有調(diào)用start()方法 |
RUNNABLE | 運(yùn)行狀態(tài)瘾杭,Java線程將操作系統(tǒng)中的就緒和運(yùn)行兩種狀態(tài)籠統(tǒng)地稱作“運(yùn)行中” |
BLOCKED | 阻塞狀態(tài),表示線程阻塞于鎖 |
WAITING | 等待狀態(tài)哪亿,表示線程進(jìn)入等待狀態(tài)粥烁,進(jìn)入該狀態(tài)表示當(dāng)前線程需要等待其他線程做出一些特定動作(通知或中斷) |
TIME_WAITING | 超時等待狀態(tài),該狀態(tài)不同于WAITING蝇棉,它是可以在指定的時間自行返回的 |
TERMINATED | 終止?fàn)顟B(tài)讨阻,表示當(dāng)前線程已經(jīng)執(zhí)行完畢 |
線程的執(zhí)行順序
Join線程的運(yùn)行順序
原理:
定時器
import java.util.Timer;
import java.util.TimerTask;
public class TraditionalTimerTest {
public static void main(String[] args) {
// new Timer().schedule(new TimerTask() {
// @Override
// public void run() {
//
// System.out.println("bombing!");
// }
// },10000);
class MyTimberTask extends TimerTask {
@Override
public void run() {
System.out.println("bombing!");
new Timer().schedule(new MyTimberTask(), 2000);
}
}
new Timer().schedule(new MyTimberTask(), 2000);
int count = 0;
while (true) {
System.out.println(count++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
0
1
bombing!
2
3
bombing!
4
5
bombing!
6
省略...
線程的互斥與同步通信
public class TraditionalThreadSynchronized {
public static void main(String[] args) {
new TraditionalThreadSynchronized().init();
}
private void init() {
final Outputer outputer = new Outputer();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("kpioneer");
}
}
}).start();
// new Thread(new Runnable() {
// @Override
// public void run() {
//
// while (true) {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// outputer.output2("Tom");
//
// }
// }
// }).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output3("Jack");
}
}
}).start();
}
static class Outputer {
public void output(String name) {
int len = name.length();
synchronized (Outputer.class) {
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
public synchronized void output2(String name) {
int len = name.length();
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
public static synchronized void output3(String name) {
int len = name.length();
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
線程同步通信技術(shù)
子線程循環(huán)10次,接著主線程循環(huán)100篡殷,接著又回到子線程循環(huán)10次钝吮,接著再回到主線程有循環(huán)100,如此循環(huán)50次板辽,請寫出程序奇瘦。
public class TraditionalThreadCommunication {
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 50; i++) {
business.sub(i);
}
}
}
).start();
for (int i = 1; i <= 50; i++) {
business.main(i);
}
}
}
/**
*要用到共同數(shù)據(jù)(包括同步鎖)的若干方法應(yīng)該歸在同一個類身上,
* 這種設(shè)計正好體現(xiàn)了高類聚和和程序的健壯性
*/
class Business {
private boolean bShouldSub = true;
public synchronized void sub(int i) {
if(!bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("sub thread sequece of " + j + ",loop of " + i);
}
bShouldSub = false;
this.notify();
}
public synchronized void main(int i) {
if(bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <=100; j++) {
System.out.println("main thread sequece of " + j + ",loop of " + i);
}
bShouldSub = true;
this.notify();
}
}
sub thread sequece of 1,loop of 1
sub thread sequece of 2,loop of 1
sub thread sequece of 3,loop of 1
sub thread sequece of 4,loop of 1
sub thread sequece of 5,loop of 1
sub thread sequece of 6,loop of 1
sub thread sequece of 7,loop of 1
sub thread sequece of 8,loop of 1
sub thread sequece of 9,loop of 1
sub thread sequece of 10,loop of 1
main thread sequece of 1,loop of 1
main thread sequece of 2,loop of 1
main thread sequece of 3,loop of 1
main thread sequece of 4,loop of 1
main thread sequece of 5,loop of 1
main thread sequece of 6,loop of 1
main thread sequece of 7,loop of 1
main thread sequece of 8,loop of 1
main thread sequece of 9,loop of 1
main thread sequece of 10,loop of 1
main thread sequece of 11,loop of 1
省略中間...
main thread sequece of 99,loop of 1
main thread sequece of 100,loop of 1
sub thread sequece of 1,loop of 2
sub thread sequece of 2,loop of 2
sub thread sequece of 3,loop of 2
sub thread sequece of 4,loop of 2
sub thread sequece of 5,loop of 2
sub thread sequece of 6,loop of 2
sub thread sequece of 7,loop of 2
sub thread sequece of 8,loop of 2
sub thread sequece of 9,loop of 2
sub thread sequece of 10,loop of 2
main thread sequece of 1,loop of 2
main thread sequece of 2,loop of 2
main thread sequece of 3,loop of 2
省略...