1.內(nèi)存中每個程序叫進程
- 一個程序中多個線程執(zhí)行
- cpu中央處理器(英特爾,amd)intel core(核心)i5
- 瀏覽器下載一個線程,下載器多個線程下載同一個文件
- 分時調(diào)度:所有線程輪流使用;搶占式調(diào)度:根據(jù)優(yōu)先級
2.thread
- 繼承thread并重寫run方法,使用start()(開啟線程)虛擬機會自動調(diào)用run方法
- Thread.sleep(10);也有靜態(tài)休眠方式
- main是一個棧,新的線程重新開一個棧,棧內(nèi)存均是相對應線程私有
- 靜態(tài)方法currentthread返回當前線程(Thread.currentThread().getName())
threadText tt=new threadText();
tt.setName("aaa");設置線程名
tt.sleep(1000);休眠,以毫秒為時間單位
tt.start();
----------
public class threadText extends Thread {
@Override
public void run() {
super.run();
System.out.println(this.getName());
}
}
3.Runnable 接口實現(xiàn)
- 耦合降低
SubRunable tt=new SubRunable();
new Thread(tt).start();
----------匿名內(nèi)部類寫法
new Thread(new Runnable() {
@Override
public void run() {
}
}).start();
-------
public class SubRunable implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"run111");
}
}
4.線程關系
- 生命周期:new,runable狀態(tài),死亡(stop)
- 在runable狀態(tài)又有幾種分別:
- 阻塞,正在等待執(zhí)行,cpu調(diào)節(jié),自動
- 休眠(sleep),可被喚醒執(zhí)行或者阻塞,時間決定
- wait等待,可被喚醒(notify()),無限時
5.線程池
- 重復利用線程池中線程,因為創(chuàng)建線程和銷毀占用大量資源
ExecutorService es = Executors.newFixedThreadPool(2);線程池放兩個線程
es.submit(new SubRunable());
es.submit(new SubRunable());
es.submit(new SubRunable());
es.shutdown();銷毀線程池,一般不用
SubRunable自定義線程對象有runable接口
兩個現(xiàn)線程同時執(zhí)行兩個任務,第三個等待空閑線程
6.callable能拋異常,有返回值
- runable不能拋異常,沒有返回值
ExecutorService es = Executors.newCachedThreadPool();
Future<String> s = es.submit(new TextCall());
System.out.println(s.get());
--------------------
public class TextCall implements Callable<String>{
@Override
public String call() throws Exception {
return "aaa";
}
}
自由定義返回值類型