多執行緒列印寶典

2022-09-07 16:27:15 字數 2471 閱讀 7693

典中典多執行緒列印題,我來歸納一下:

三個執行緒分別列印 a,b,c,要求這三個執行緒一起執行,列印 n 次,輸出形如「abcabcabc....」的字串

這一招也是我最喜歡的,簡單無腦

public class main ;

public static void main(string args)

} catch (interruptedexception e)

}).start();

new thread(() ->

} catch (interruptedexception e)

}).start();

new thread(() ->

} catch (interruptedexception e)

}).start();}}

public class main 

public static void main(string args) , "a").start();

new thread(() -> , "b").start();

new thread(() -> , "c").start();

}public void printletter(int targetstatus, condition current, condition next)

++status;

++i;

system.out.print(thread.currentthread().getname());

next.signal();

} catch (exception e) finally }}

}

使用lock/condition的話雖說**比semaphore複雜,但是可以做到精準控制,比如,aa 列印 5 次,bb 列印10 次,cc 列印 15 次,重複 10 次

locksupport 是 jdk 底層的基於sun.misc.unsafe來實現的類,用來建立鎖和其他同步工具類的基本執行緒阻塞原語。它的靜態方法unpark()park()可以分別實現阻塞當前執行緒和喚醒指定執行緒的效果,所以用它解決這樣的問題會更容易一些。

public class main 

}, "a");

threads[1] = new thread(() ->

}, "b");

threads[2] = new thread(() ->

}, "c");

for (thread t : threads) }}

這種方法與semaphore有異曲同工之妙,也是十分簡單的一種方式!

交替列印奇偶數字

public class main , "even:").start();

new thread(() -> , "odd:").start();

}public void printnum(int times, int targetstatus, condition current, condition next)

system.out.print(thread.currentthread().getname() + status + " ");

++status;

next.signal();

} catch (exception e) finally }}

}

使用locksupport一如既往的簡單易懂。

public class main 

}, "even:");

threads[1] = new thread(() ->

}, "odd:");

for (thread t : threads) }}

------------恢復內容結束------------

多執行緒迴圈列印

public class multithread implements runnable public static void main string args 實現run方法,將自定義執行緒的任務定義在run方法上 public void run 輸出結果 執行緒一列印a 執行緒二列印b 執行緒三...

多執行緒列印問題

最近面試遇到乙個多執行緒的題目,對方要求用多個執行緒列印abcabc 每個執行緒負責列印其中乙個字母。迴圈10次吧!public class test thread threads newthread 3 for int i 0 i threads.length i 列印執行緒 class prin...

JAVA多執行緒列印ABC

多執行緒中乙個很有名的例題就是多執行緒列印 abc,要求用三個執行緒,分別是列印 a,列印 b,列印 c,輪流喚醒和鎖死,最終列印出10組 abc。created by 123 on 2016 8 30.public class printabc 將列印a,列印b,列印c分別列為三個互斥的方法,寫在...