1.關於併發
併發:並行的執行程序的多個部分。
併發能解決的問題大體上可以分爲“速度”(併發通常是提高運行在單處理器上的程序的性能)和“設計可管理性”兩種。
併發編程使我們可以將程序劃分爲多個分離的獨立運行的任務。
2.實戰
2.1線程可以驅動任務,要想定義任務,只需實現Rnnable接口並編寫run()方法,使得該任務可以執行你的命令。
2.1.1任務一
LifTOff.java
<span style="font-size:18px;">public class LifTOff implements Runnable{
protected int countDown = 10;
private static int taskCount=0;
private final int id = taskCount++;
public LifTOff() {
super();
}
public LifTOff(int countDown) {
this.countDown = countDown;
}
public String status() {
return "#"+id+"("+(countDown > 0 ? countDown : "Liftoff!")+").";
}
@Override
public void run() {
while (countDown-- > 0) {//10次循環
System.out.println(status());
Thread.yield();
//讓線程回到可執行狀態
}
}
}
</span>
2.1.2任務二Second.java
<span style="font-size:18px;">public class Second implements Runnable{</span><pre name="code" class="java"><span style="font-size:18px;"> protected int countDown = 10;
private static int taskCount=0;
private final int id = taskCount++;
public H() {
super();
}
public H(int countDown) {
this.countDown = countDown;
}
public String status() {
return "#"+id+"("+(countDown > 0 ? countDown : "Liftoff!")+").";
}
@Override
public void run() {
while (countDown-- > 0) {//10次循環
System.out.println(status());
Thread.yield();
//讓線程回到可執行狀態
}
}}</span>
2.2將Runnable對象轉變爲工作任務的傳統方式是把他提交給一個Thread構造器
MoreBasicThreads.java
<span style="font-size:18px;">public class MoreBasicThreads {
public static void main(String[] args) {
Thread t = new Thread(new LifTOff());
Thread t2 = new Thread(new H());
t.start(); //現調用start()方法初始化線程,再調用run()方法啓動該任務。
t2.start();//現調用start()方法初始化線程,再調用run()方法啓動該任務。
System.out.println("Hello World!!!");
}
}
</span>
執行結果
總結:任務並非是順序執行而是是併發執行的(添加Sleep()方法可以使併發更加明顯)