并發(fā):當(dāng)有多個(gè)線程在操作時(shí),如果系統(tǒng)只有一個(gè)CPU,則它根本不可能真正同時(shí)進(jìn)行一個(gè)以上的線程求冷,它只能把CPU運(yùn)行時(shí)間劃分成若干個(gè)時(shí)間段,再將時(shí)間 段分配給各個(gè)線程執(zhí)行,在一個(gè)時(shí)間段的線程代碼運(yùn)行時(shí)结澄,其它線程處于掛起狀发框。.這種方式我們稱之為并發(fā)(Concurrent)跟畅。
并行:當(dāng)系統(tǒng)有一個(gè)以上CPU時(shí),則線程的操作有可能非并發(fā)棚蓄。當(dāng)一個(gè)CPU執(zhí)行一個(gè)線程時(shí)哟楷,另一個(gè)CPU可以執(zhí)行另一個(gè)線程瘤载,兩個(gè)線程互不搶占CPU資源,可以同時(shí)進(jìn)行卖擅,這種方式我們稱之為并行(Parallel)鸣奔。
區(qū)別:并發(fā)和并行是即相似又有區(qū)別的兩個(gè)概念,并行是指兩個(gè)或者多個(gè)事件在同一時(shí)刻發(fā)生惩阶;而并發(fā)是指兩個(gè)或多個(gè)事件在同一時(shí)間間隔內(nèi)發(fā)生挎狸。在多道程序環(huán)境下,并發(fā)性是指在一段時(shí)間內(nèi)宏觀上有多個(gè)程序在同時(shí)運(yùn)行断楷,但在單處理機(jī)系統(tǒng)中锨匆,每一時(shí)刻卻僅能有一道程序執(zhí)行,故微觀上這些程序只能是分時(shí)地交替執(zhí)行冬筒。倘若在計(jì)算機(jī)系統(tǒng)中有多個(gè)處理機(jī)恐锣,則這些可以并發(fā)執(zhí)行的程序便可被分配到多個(gè)處理機(jī)上,實(shí)現(xiàn)并行執(zhí)行账千,即利用每個(gè)處理機(jī)來處理一個(gè)可并發(fā)執(zhí)行的程序侥蒙,這樣,多個(gè)程序便可以同時(shí)執(zhí)行
基本的線程機(jī)制
1.定義任務(wù)
<code>import java.util.concurrent.TimeUnit;
public class Liffoff implements Runnable{
protected int countDown = 10;
private int taskCount = 0;
private int id = taskCount ++;
public Liffoff(){}
public Liffoff(int countDown){
this.countDown = countDown;
}
public String status(){
return "#" + id + "(" + (countDown > 0 ? countDown : "Liffoff") + ")\t";
}
@Override
public void run() {
while(countDown -- > 0){
System.out.print(status());
//Thread.yield(); //線程調(diào)度器
try {
//Thread.sleep(1000);
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println();
}
public static void main(String[] args) {
Liffoff lif = new Liffoff();
lif.run();
}
}
</code>
在run()中對(duì)靜態(tài)方法通常Thread.yield()的調(diào)用是對(duì)線程調(diào)度器(Java線程機(jī)制的一部分匀奏,可以將一個(gè)CPU從一個(gè)線程轉(zhuǎn)移給另外一個(gè)線程)的一種建議
2.Thead 類
將Runnable對(duì)象轉(zhuǎn)變?yōu)楣ぷ魅蝿?wù)的傳統(tǒng)方式是把它提交給一個(gè)Thread構(gòu)造器
<code>public class BasicThread {
public static void main(String[] args) {
Thread t = new Thread(new Liffoff());
t.start();
System.out.println("waiting for Liffoff()");
}
}
</code>
Thread構(gòu)造器只需要一個(gè)Runnable對(duì)象鞭衩。調(diào)用Thread對(duì)象的start()方法為該線程執(zhí)行必須的初始化操作,然后調(diào)用Runnable的run()方法以便在這個(gè)新線程中啟動(dòng)該任務(wù)娃善。
3.使用Executor
Java SE5的java.util.concurrent包中的執(zhí)行器(Executor)將為你管理Thread對(duì)象论衍,從而簡(jiǎn)化了并發(fā)編程。Executor在客戶端和執(zhí)行之間提供了一個(gè)間接層
<code>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CachedThreadPool {
public static void main(String[] args) {
//ExecutorService exec = Executors.newCachedThreadPool();
//ExecutorService exec = Executors.newFixedThreadPool(5);
ExecutorService exec = Executors.newSingleThreadExecutor();
for(int i=0;i<3;i++){
exec.execute(new Liffoff());
}
exec.shutdown();
}
}
</code>
- CachedThreadPool:在程序執(zhí)行過程中通常會(huì)創(chuàng)建于所需數(shù)量相同的線程聚磺,然后在它回收舊線程時(shí)停止創(chuàng)建新的線程坯台,因此它是合理的Executor的首選
- FixedThreadPool:可以一次性預(yù)先執(zhí)行代價(jià)高昂的線程分配,因而也就是限制線程的數(shù)量瘫寝,這可以節(jié)省時(shí)間
- SingleThreadExecutor:就像是線程數(shù)量為一的FixedThreadPool蜒蕾,如果向SingleThreadExecutor提交了多個(gè)任務(wù),那么這個(gè)任務(wù)將會(huì)排隊(duì)
4.從任務(wù)中產(chǎn)生返回值
<code>import java.util.concurrent.Callable;
public class TaskWithResult implements Callable<String>{
int id;
public TaskWithResult(int id){
this.id = id;
}
@Override
public String call() throws Exception {
return "result " + id;
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableDemo {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
List<Future<String>> str = new ArrayList<Future<String>>();
for(int i=0;i<10;i++){
str.add(exec.submit(new TaskWithResult(i)));
}
for(Future<String> s : str){
try {
System.out.println(s.get()+"\t");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}
</code>
5.休眠
影響任務(wù)行為的一種簡(jiǎn)單方法是調(diào)用sleep()焕阿,這將使任務(wù)終止執(zhí)行給定的時(shí)間咪啡,對(duì)sleep()的調(diào)用會(huì)拋出InterruptedException異常,并且你可以看到暮屡,它在run()中被捕獲撤摸,因?yàn)楫惓2荒芸缇€程傳播會(huì)Main,所以你必須在本地處理所有在任務(wù)內(nèi)部產(chǎn)生的異常:
6.優(yōu)先級(jí)
線程的優(yōu)先級(jí)將該線程的重要性傳遞給了調(diào)度器。盡管CPU處理現(xiàn)有線程集的順序是不確定的但是調(diào)度器更傾向于讓優(yōu)先級(jí)高的先執(zhí)行。
JDK共有10個(gè)優(yōu)先級(jí)
<code>package priority;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimplePriority implements Runnable {
int countDown = 5;
volatile double d;
int priority;
public SimplePriority(int priority) {
this.priority = priority;
}
public String toString() {
return Thread.currentThread() + ":" + countDown;
}
@Override
public void run() {
Thread.currentThread().setPriority(priority);
while (true) {
for (int i = 0; i < 100000; i++) {
d += (Math.PI + Math.E) / (double) i;
if (i % 1000 == 0) {
Thread.yield();
}
System.out.println(this);
if (--countDown == 0)
return;
}
}
}
public static void main(String[] args) {
ExecutorService exe = Executors.newCachedThreadPool();
for (int i = 0; i < 3; i++) {
exe.execute(new SimplePriority(Thread.MAX_PRIORITY));
}
exe.execute(new SimplePriority(Thread.MAX_PRIORITY));
exe.shutdown();
}
}
</code>
7.讓步
<code>
Thread.yield()
</code>
8.后臺(tái)線程
后臺(tái)線程是指程序運(yùn)行的時(shí)候在后臺(tái)提供一種通用服務(wù)的線程准夷,并且這種線程并不屬于程序中不可或缺的部分钥飞。因此當(dāng)所有的后天線程結(jié)束時(shí),程序也就終止 了
<code>
package daemon;
import java.util.concurrent.TimeUnit;
public class SimpleDaemons implements Runnable{
@Override
public void run() {
while(true){
try {
TimeUnit.MILLISECONDS.sleep(1500);
System.out.println("current thread " + this);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception{
for(int i=0;i<10;i++){
Thread daemon = new Thread(new SimpleDaemons());
daemon.setDaemon(true);
daemon.start();
}
TimeUnit.MILLISECONDS.sleep(1500);
}
}
</code>
9.捕獲異常
由于線程的本質(zhì)特性衫嵌,使得你不能捕獲線程中逃逸的異常读宙,一旦線程掏出任務(wù)的run()方法,他就會(huì)想外傳播到控制臺(tái)楔绞,除非你采取特殊的步驟捕獲這種錯(cuò)誤的異常
<code>package ThreadException;
public class ExceptionThread2 implements Runnable{
@Override
public void run() {
Thread t = Thread.currentThread();
System.out.println("run by t" + t);
System.out.println("en :"+ t.getUncaughtExceptionHandler());
throw new RuntimeException();
}
}
package ThreadException;
import java.util.concurrent.ThreadFactory;
public class HandleThreadFactory implements ThreadFactory{
@Override
public Thread newThread(Runnable r) {
System.out.println("create new thread "+this);
Thread t = new Thread(r);
System.out.println("create t "+t);
t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
System.out.println("en " + t.getUncaughtExceptionHandler());
return t;
}
}
package ThreadException;
public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("catch : "+e);
}
}
package ThreadException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Exception {
public static void main(String[] args) {
ExecutorService exe = Executors.newCachedThreadPool(new HandleThreadFactory());
exe.execute(new ExceptionThread2());
}
}
</code>
共享受限資源
1.不正確的訪問資源
<code>
package ShareResource;
public abstract class IntGenerator {
private volatile boolean canceled = false;
public abstract int next();
public void cancle(){ canceled = true;}
public boolean isCanceled(){return canceled;}
}
package ShareResource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class EventGenerator extends IntGenerator{
private int currentEventValue = 0;
@Override
public int next() {
++currentEventValue;//遞增過程任務(wù)可能被線程機(jī)制掛起论悴,因此遞增不是原子性操作
//Thread.yield();
++currentEventValue;
return currentEventValue;
}
public static void main(String[] args) {
EvenCheck.test(new EventGenerator());
}
}
package ShareResource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class EvenCheck implements Runnable{
private IntGenerator generator;
private final int id;
public EvenCheck(IntGenerator generator,int id){
this.id = id;
this.generator = generator;
}
@Override
public void run() {
while(!generator.isCanceled()){
int val = generator.next();
if((val % 2) != 0){
System.out.println(val + "is not even");
generator.cancle();
}
}
}
public static void test(IntGenerator generator,int count){
ExecutorService exe = Executors.newCachedThreadPool();
for(int i=0;i < count;i++){
exe.execute(new EvenCheck(generator, i));
}
exe.shutdown();
}
public static void test(IntGenerator generator){
test(generator,10 );
}
}
</code>
輸出結(jié)果:
<code>
5 is not even
3 is not even
7 is not even</code>
從輸出結(jié)果可知,產(chǎn)生了奇數(shù)墓律,一個(gè)任務(wù)有可能在另一個(gè)任務(wù)執(zhí)行第一個(gè)currentEventValue的遞增操作之后,但是沒有執(zhí)行第二個(gè)操作之前幔亥,調(diào)用了next()方法,這就是線程沖突针肥,多個(gè)線程共享一個(gè)變量
2.解決共享資源競(jìng)爭(zhēng)
java以提供關(guān)鍵字synchronized的形式,為防止資源沖突提供內(nèi)置支持,當(dāng)任務(wù)要執(zhí)行synchronized關(guān)鍵字保護(hù)的代碼片段時(shí)蜂厅,他將檢查鎖是否可用,然后回去鎖,執(zhí)行代碼改橘,釋放鎖唧龄。當(dāng)在對(duì)象上調(diào)用其任意synchronized方法的時(shí)候讽挟,此對(duì)象都被加鎖,這時(shí)該對(duì)象上的其他synchronized方法只有等到前一個(gè)方法調(diào)用完畢并釋放鎖之后才能被調(diào)用
<code>@Override
public synchronized int next() { //同步鎖
//lock.lock();
++currentEventValue;//遞增過程任務(wù)可能被線程機(jī)制掛起,因此遞增不是原子性操作
++currentEventValue;
return currentEventValue;
}
</code>
這樣才不會(huì)有奇數(shù)出現(xiàn)