多線程這一塊知識的話最重要的就是代理池的非同步技術,這塊會大大提高我們以後編寫的工具的運行效率。值得學習 ...
0x00前言和思維導圖
1.什麼是進程?什麼事線程?
我們可以這樣理解,一個qq相當於一個進程,你同時間跟幾個人聊qq你每一個聊天框就相當於線程(線程就是進程的每一個執行場景/執行單元).
2.對於java來說?
啟動JVM虛擬機然後再調用一個main()方法,同時也會調用一個垃圾回收線程負責看護和回收垃圾,最少現在java有兩個併發的線程。
3.進程和線程之間的關係。
(1)進程(A)和進程(B)之間記憶體獨立不共用
(2)同一個進程下的,線程(A)和線程(B)堆記憶體和方法區共用。
(3)但是棧記憶體獨立一個線程一個棧
0x01線程的基礎使用
0x1重新構造run方法和繼承Runnable介面
方法1:重新構造方法
用你自己的類去繼承Thread類重寫run方法,有缺陷當你的線程不止一個需要很多線程的時候你使用這種方法需要去重載run方法
public class JAVA_Threads extends Thread {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("我是子線程"+i);
}
}
public static void main(String[] args) {
JAVA_Threads threads=new JAVA_Threads();
threads.start();
for (int i = 0; i < 100; i++) {
System.out.println("我是主線程"+i);
}
}
}
方法二:繼承Runnable實現run方法
1.繼承介面去實現介面裡面的類方法,去面向介面編程,符合面向對象編程的思維。
2.這樣去繼承介面以後還可以繼承其他類,增強代碼的多變性。
class Threads_Test2{
public static void main(String[] args) {
Thread thread1=new Thread(new My_thread_run());
Thread thread2=new Thread(new My_thread_run2());
thread1.start();
thread2.start();
}
}
class My_thread_run implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("這是子線程"+i);
}
}
}
class My_thread_run2 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("我是子線程2個"+i);
}
}
}
方法三:匿名內部類構造
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("我是子線程");
}
};
new Thread(r).start();
System.out.println("我是主線程");
}
方法四:Callable介面的實現
1.這種方式可獲取線程返回的結果;
class CallableTest {
public static void main(String[] args) throws Exception {
MyThread mt = new MyThread();
FutureTask<Integer> result = new FutureTask<Integer>(mt);
new Thread(result).start();
// 獲取運算結果是同步過程,即 call 方法執行完成,才能獲取結果
Integer sum = result.get();
System.out.println(sum);
}
}
class MyThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 100; i++) {
System.out.println("我在執行");
}
return sum;
}
}
0x2獲取一些其他方法
1.設置和獲取線程的名字
a.進程對象.getName(); public final String getName()
b.進程對象.setName(); public final synchronized void setName(String name)
2.獲取當前進程的名字
a.public static native Thread currentThread();
b.返回的對象是一個線程,用這個線程的Thread.getName
class Mythread_Testo2{
public static void main(String[] args) {
Thread thread=new Thread(new My_thread_run2());
System.out.println(thread.getName());
thread.setName("我是你子線程");
System.out.println(thread.getName());
Thread hell= Thread.currentThread();
System.out.println(hell.getName());
}
}
0x03sleep()的方法
1.看看源碼public static native void sleep(long millis)
a.這個方法是一個靜態的方法。直接用類名.的方法調用。
b.出現在哪裡哪裡睡眠,出現在main就是main睡眠。
class Mythread_Test3{
public static void main(String[] args) {
Thread thread=new Thread(new My_thread_run2());
thread.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("執行完成");
}
}
2.中止睡眠
a.public void interrupt()
b.使用該方法以後會爆出錯誤就是cath塊的指令列印錯誤信息
點擊查看代碼
java.lang.InterruptedException: sleep interrupted
at java.base/java.lang.Thread.sleep(Native Method)
at com.zhonglin.www.My_thread_run2.run(JAVA_Threads.java:44)
at java.base/java.lang.Thread.run(Thread.java:833)
//睡眠被打斷錯誤信息
class Mythread_Test3{
public static void main(String[] args) {
Thread thread=new Thread(new My_thread_run2());
thread.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
System.out.println("執行完成");
}
}
0x4join()方法
1.public final void join()
2。會將線程合併(插入)到當前線程中間,阻塞當前線程,直到插入線程完成以後才繼續當前線程。
class Mythread_Test3{
public static void main(String[] args) {
Thread thread=new Thread(new My_thread_run2());
System.out.println("我正在執行");
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("執行完成");
}
}
0x03線程安全
1。最簡單的例子,當你手寫腳本進行弱口令爆破的時候,多線程會明顯提高你的效率,你去遍歷字典的時候會發生一種情況,第一個線程readline了第一行,如果沒有線程安全你的第二個線程可能還是readlin的字典的第一行。
2.非同步=併發,同步=排隊
0x1同步代碼塊synchironized
1.synchironized(),這個括弧中間的一定你想要排隊執行的的共同對象,比如說如果要去取錢一個在ATM取錢是線程1,一個在銀行櫃臺取錢是線程2,那麼它們的共同對象就是那個銀行賬戶
2.工作機制,每一個線程運行到synchironized前面的時候都會去對比對象,看是否是共用對象,如是相同對象那麼就會獲取鎖,下一個線程過來發現也是共用對象的話就會等待鎖的釋放,再獲得鎖。
public static class sunchironize_teset implements Runnable{
private int num = 100;
private boolean flag = true;
Object obj = new Object();
@Override
public void run() {
while (flag){
synchronized (obj){
if (num==0){
flag = false;
}else {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("我是子線程"+Thread.currentThread()+"數值"+num--);
}
}
}
}
}
public class Test_1 {
public static void main(String[] args) {
sunchironize_teset r= new sunchironize_teset();
new Thread(r).start();
new Thread(r).start();
new Thread(r).start();
new Thread(r).start();
new Thread(r).start();
}
}}
0x2進階lock和unlock方法
class MyLockStudy implements Runnable {
private int count;
Lock l = new ReentrantLock();
@Override
public void run() {
l.lock();
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": 我在執行");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
l.unlock();
}
public static void main(String args[]) {
MyLockStudy runn = new MyLockStudy();
Thread thread1 = new Thread(runn, "thread1");
Thread thread2 = new Thread(runn, "thread2");
Thread thread3 = new Thread(runn, "thread3");
thread1.start();
thread2.start();
thread3.start();
}
}
0x04線程池
0x1:newFixedThreadPool
1.構造函數:public static ExecutorService newFixedThreadPool(int nThreads)
2.創建的是一個固定大小的線程池創造的大小取決有傳入構造參數的int nThreads
3.如果當前線程池的線程被占滿剩下的線程會進入等待等待前面的線程結束以後進入隊列進行執行。
4.
class Mypool_1{
public static void main(String[] args) {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);//創建一個線程池
for (int i = 0; i < 5; i++) {
final int index = i;
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat( "HH:mm:ss");
System.out.println("運行時機是"+simpleDateFormat.format(new Date())+" "+index);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
fixedThreadPool.shutdown();
}
//執行的結果是
// 運行時間是20:03:57 2
// 運行時間是20:03:57 0
// 運行時間是20:03:57 1
// 運行時間是20:03:59 4
// 運行時間是20:03:59 3
}
0x2:newCachedThreadPool
1.構造函數:
點擊查看代碼
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
class Mypool_2{
public static void main(String[] args) {
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
int index=i;
cachedThreadPool.execute(new Runnable() {
@Override
public void run() {
SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss");
System.out.println("運行的時間"+sdf.format(new Date())+" "+index);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
cachedThreadPool.shutdown();
// 運行的時間20:04:39 1
// 運行的時間20:04:39 3
// 運行的時間20:04:39 2
// 運行的時間20:04:39 4
// 運行的時間20:04:39 0
}
}
0x3:newSingleThreadExecutor
1.它創建了一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有任務按照指定順序執行。
2.為什麼是單線程?的單線程執行指的是線程池內部,從線程池外的角度看,主線程在提交任務到線程池時並沒有阻塞,仍然是非同步的。
class Mypool_3{
public static void main(String[] args) {
ExecutorService singethreadpool=Executors.newSingleThreadExecutor();
for (int i = 0; i < 5; i++) {
int index=i;
singethreadpool.execute(new Runnable() {
@Override
public void run() {
SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss");
System.out.println("運行的時間是"+sdf.format(new Date())+" "+index);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}singethreadpool.shutdown();
// 運行的時間是20:37:17 0
// 運行的時間是20:37:19 1
// 運行的時間是20:37:21 2
// 運行的時間是20:37:23 3
// 運行的時間是20:37:25 4
}
}
0x4:newScheduledThreadPool
1.這個方法創建了一個固定大小的線程池,支持定時及周期性任務執行。
看一下延遲執行
class Mypool_4 {//延遲三秒運行
public static void main(String[] args) {
final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
System.out.println("提交時間: " + sdf.format(new Date()));
scheduledThreadPool.schedule(new Runnable() {
@Override
public void run() {
System.out.println("運行時間: " + sdf.format(new Date()));
}
}, 3, TimeUnit.SECONDS);
scheduledThreadPool.shutdown();
}
// 提交時間: 20:50:55
// 運行時間: 20:50:58
}
看一下周期方法:使用該線程池的scheduleAtFixedRate方法,延遲1秒鐘後每隔3秒執行一次任務,運行結果如下:
class Mypool_5 {
public static void main(String[] args) {
final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
System.out.println("提交時間: " + sdf.format(new Date()));
scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("運行時間: " + sdf.format(new Date()));
}
}, 1, 3, TimeUnit.SECONDS);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
scheduledThreadPool.shutdown();
}
}
0x5小結
其實線程池還有很多方法沒有去學習,只是現在在這裡大概的學習一下,以後在開發java多線程工具的時候會深入的瞭解。以下各線程池的特點
CachedThreadPool:可緩存的線程池,該線程池中沒有核心線程,非核心線程的數量為Integer.max_value,就是無限大,當有需要時創建線程來執行任務,沒有需要時回收線程,適用於耗時少,任務量大的情況。
SecudleThreadPool:周期性執行任務的線程池,按照某種特定的計劃執行線程中的任務,有核心線程,但也有非核心線程,非核心線程的大小也為無限大。適用於執行周期性的任務。
SingleThreadPool:只有一條線程來執行任務,適用於有順序的任務的應用場景。
FixedThreadPool:定長的線程池,有核心線程,核心線程的即為最大的線程數量,沒有非核心線程
0x05總結
多線程這一塊知識的話最重要的就是代理池的非同步技術,這塊會大大提高我們以後編寫的工具的運行效率。值得學習