java多線程練習題
① java的龜兔賽跑多線程問題
publicclassCompetition{
=false;//用來標記是否有人到達終點,到達終點後游戲結束
//烏龜的實現方式
{
privatevolatileinttotal=0;//用來記錄當前已經前行了多少距離
@Override
publicvoidrun(){
while(!gameOver){
intstep=(int)(Math.random()*5+1);//產生1-5的隨機數
total+=step;
try{
Thread.sleep(200);
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
publicintgetTotal(){
returntotal;
}
}
//兔子的實現方式
{
privatevolatileinttotal=0;
@Override
publicvoidrun(){
while(!gameOver){
intstep=(int)(Math.random()*5+1);
total+=step;
try{
Thread.sleep(200);
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
publicintgetTotal(){
returntotal;
}
}
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
finalTortoisetortoise=newTortoise();
finalRabbitrabbit=newRabbit();
newThread(tortoise).start();
newThread(rabbit).start();
//下面多起了一個線程,相當於比賽的時候的裁判員,他每隔一段時間就看一下是否有人到達終點,若有人到達則宣判該人獲勝,游戲結束
newThread(newRunnable(){
@Override
publicvoidrun(){
//TODOAuto-generatedmethodstub
while(!gameOver){
inttorLen=tortoise.getTotal();//獲得烏龜前行的距離
intrabLen=rabbit.getTotal();//獲得兔子前行的距離
System.out.println("烏龜:"+torLen+",兔子"+rabLen);
if(torLen>=100&&rabLen<100){
System.out.println("烏龜獲勝!!!");
gameOver=true;
}elseif(rabLen>=100&&torLen<100){
System.out.println("兔子獲勝!!!");
gameOver=true;
}elseif(rabLen>=100&&torLen>=100){//這里有可能兩人同時到達終點
System.out.println("同時到達終點!!!");
gameOver=true;
}
try{
Thread.sleep(210);
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
}).start();
}
② java多線程猜數字問題
package practice12;
/**
* @Author: HuDaoquan
* @Description: TODO
* @Email: [email protected]
* @Date: 2020-6-20 1:01
* @Version 1.0
*/
public class Number implements Runnable {
final int SMALLER = -1, LARGER = 1, SUCCESS = 888;
int realNumber, guessNumber, min = 0, max = 100, message = SMALLER;
boolean pleaseGuess = false, isGiveNumber = false;
Thread giveNumberThread, guessNumberThread;
Number() {
giveNumberThread = new Thread(this);
guessNumberThread = new Thread(this);
}
@Override
public void run() {
for (int count = 1; count < 10; count++) {
System.err.println(count + " " + message + Thread.currentThread().getName());
setMessage(count);
if (message == SUCCESS) {
return;
} else {
continue;
}
}
}
public synchronized void setMessage(int count) {
if (Thread.currentThread() == giveNumberThread && isGiveNumber == false) {
realNumber = (int) (Math.random() * 100 + 1);
System.out.println("我在心裡想了一個1-100的數,你猜猜看,它是多少?====" + realNumber);
isGiveNumber = true;
// 讓下面的判斷語句執行猜線程
pleaseGuess = true;
}
if (Thread.currentThread() == giveNumberThread && isGiveNumber == true) {
//pleaseGuess為true,調用猜線程,猜線程將pleaseGuess置為false,結束循環,也就是在此調用猜線程
while (pleaseGuess == true) {
try {
wait();
// 猜線程執行完,猜線程將pleaseGuess置為false,下一次循環退出while,執行後續if語句
} catch (InterruptedException e) {
}
}
// 調用完一次猜,開始判斷猜的結果並給出message信息
if (realNumber > guessNumber) {
message = SMALLER;
System.out.println(guessNumber + "你猜小了,大點試試!");
} else if (realNumber < guessNumber) {
message = LARGER;
System.out.println(guessNumber + "你猜大了,小點試試");
} else {
message = SUCCESS;
System.out.println(guessNumber + "太棒啦,你猜對了呢");
}
// 給完信息,將pleaseGuess置為true,給猜線程調用的時候退出wait;也就是開始猜
pleaseGuess = true;
}
if (Thread.currentThread() == guessNumberThread && isGiveNumber == true) {
// 讀到猜線程為false,則調用wait,停止猜,調用給線程
while (pleaseGuess == false) {
try {
wait();
// 給線程執行完會將pleaseGuess置為true,此處下一次循環即會結束wait調用,執行後續語句
} catch (InterruptedException e) {
}
}
// 開始猜
if (message == SMALLER) {
min = guessNumber;
guessNumber = (min + max) / 2;
System.out.println("我第" + count + "次猜這個數是" + guessNumber);
} else if (message == LARGER) {
max = guessNumber;
guessNumber = (min + max) / 2;
System.out.println("我第" + count + "次猜這個數是" + guessNumber);
}
pleaseGuess = false;
}
notifyAll();
}
public static void main(String[] args) {
Number number = new Number();
number.giveNumberThread.start();
number.guessNumberThread.start();
}
}
運行結果
③ 璇劇▼璁捐¢樼洰錛屽氱嚎紼嬬紪紼嬶細鍖婚櫌闂ㄨ瘖妯℃嫙錛屾兂鐢╦ava瀹炵幇錛屾眰澶х炴寚鐐
鍏稿瀷鐨勭敓浜ц呮秷璐硅呮ā鍨嬨
浜嗚Вj5鐨勫苟鍙戝簱錛岄偅涓騫跺彂搴撲腑鏈夐傚悎緇勪歡瀹炵幇銆
濡傛灉涓嶄簡瑙o紝榪欎箞鏉ワ細
鍒涘緩涓涓闃熷垪錛屾ら槦鍒楄佹眰綰跨▼瀹夊叏錛屽傛灉闃熷垪涓虹┖鍒欐秷璐硅呴樆濉炪傚傛灉闃熷垪杈懼埌鏌愪釜鏈澶у礆紝鍒欓樆濉炵敓浜ц呫
闃熷垪鐢錛屾櫘閫氱殑list鎴栧疄鐜板ソ鐨勯槦鍒楀寘瑁呮垚綰跨▼瀹夊叏鐨勩
鐢╯ynchronized鍚屾ュ師鏂規硶鎴栦唬鐮佸潡銆
鍐欎竴涓鎴杗涓綰跨▼錛屾ā鎷熺棶浜猴紝鎺掗槦鍔炵悊涓氬姟錛屽線涓婇潰鐨勯槦鍒椾腑娣誨姞鏁版嵁銆
褰撹揪鍒伴槦鍒楃殑鏈澶у圭Н錛岄樆濉烇紝絳夊緟鐢熶駭鑰呯嚎紼嬪彇鏁版嵁銆
闃誨烇細makerLock.wait();//鉶氭嫙鏈轟細鍑鴻╃嚎紼嬫寕璧鳳紝鍏跺疄灝辨槸鎿嶄綔緋葷粺錛屼繚瀛樺綋鍓嶇嚎紼嬪湪cpu涓婄殑榪愯岀姸鎬併傚啀鍑鴻╃嚎紼嬫e湪浣跨敤鐨刢pu璧勬簮錛屽崰鐢ㄧ殑鍐呭瓨涓嶄細閲婃斁銆
寰闃熷垪鎻掑叆鏁版嵁鐨勬椂鍊欙紝鍥犱負涓嶇煡閬撴槸鍚︽湁娑堣垂鑰呭勪簬絳夊緟鐘舵侊紝閫氱煡娑堣垂鑰咃細
customerLock.notifyAll();//鉶氭嫙鏈鴻皟搴︽秷璐硅呯嚎紼嬭繍琛岋紝瀹為檯涓婃槸鎿嶄綔緋葷粺錛屾妸淇濆瓨鐨勬秷璐硅呯嚎紼嬬姸鎬侊紝浠庢柊鍔犺澆鍒癱pu涓鎺ョ潃榪愯屻傛帴鐫榪愯岀嚎紼嬫槸浠繪剰鐨勶紝鍙栧喅浜庝笉鍚屾搷浣滅郴緇熺殑綰跨▼璋冨害綆楁硶銆
娑堣垂鑰呯嚎紼嬭誨彇涓涓鏁版嵁鍚庯紝瑕侀氱煡鐢熶駭鑰咃紝鍙浠ョ戶緇錛岄亾鐞嗗悓涓婏細
makerLock.notifyAll();
闃熷垪涓錛屾棤鏁版嵁鍙璇葷殑鏃跺欙細
customerLock.wait();//鍘熺悊鍚屼笂錛
鏈鍚庢敞鎰忥紝鐢熶駭鑰呰窡娑堣垂鑰呬嬌鐢ㄤ簡涓や釜涓嶅悓鐨勫硅薄閿併俵ock.wait()鐨勪嬌鐢ㄦ柟娉曟槸榪欐牱鐨勶細
synchronized(lock){
......
while(condition==true){
lock.wait();
}
......
Objecto=queen.pop();
lock.notifyAll();
}
鏈鍚庡惎鍔╪涓綰跨▼璇婚槦鍒楋紝妯℃嫙鍔炵悊涓氬姟鐨勭獥鍙o紱n涓綰跨▼鍐欓槦鍒楋紝妯℃嫙鐥呬漢鎺掗槦銆
鏂扮嚎紼嬪簱涔熸湁璺熻佺嚎紼嬪簱瀵瑰簲鐨勬柟娉曪紝鏂扮嚎紼嬪簱鏈夌嚎紼嬪畨鍏ㄧ殑楂樻晥闃熷垪銆傛病鏈変笂闈㈤夯鐑︼紝浣嗕笂闈㈠啓鐨勬槸鐞嗚В鏂扮嚎紼嬫暟鎹緇撴瀯涓庡疄鐜扮殑鍩虹銆
packagecom.;
importjava.util.LinkedList;
importjava.util.List;
importjava.util.Random;
publicclassTestThread2{
//緙撳啿涓婇檺
privatelongbufsize;
//緙撳啿
privateList<String>buf;
publicTestThread2(){
bufsize=5;
buf=newLinkedList<String>();
}
//鐢熶駭鑰呰皟鐢
publicvoidput(Strings){
//妯℃嫙鐢熶駭鑰呰窡涓嶄笂娑堣垂鑰
/*
try{
Thread.sleep(100);
}catch(InterruptedExceptione){
}
*/
synchronized(this){
//瓚呰繃闃熷垪闄愬埗灝辯瓑寰
while(buf.size()==bufsize){
System.out.println("闃熷垪宸叉弧錛岀敓浜ц:"+Thread.currentThread().getId()+"寮濮嬬瓑寰呫");
try{
this.wait();
}catch(InterruptedExceptione){
}
}
buf.add(s);
//閫氱煡娑堣垂鑰
this.notifyAll();
}
}
//娑堣垂鑰呰皟鐢
synchronizedpublicStringtake(){
//妯℃嫙娑堣垂鑰呰窡涓嶄笂鐢熶駭鑰
try{
Thread.sleep(100);
}catch(InterruptedExceptione){
}
Strings=null;
synchronized(this){
while(buf.size()==0){
System.out.println("闃熷垪涓虹┖錛屾秷璐硅:"+Thread.currentThread().getId()+"寮濮嬬瓑寰呫");
try{
this.wait();
}catch(InterruptedExceptione){
}
}
//鍙栧厛鏀懼叆鐨勫厓緔狅紝騫剁Щ闄
s=buf.get(0);
buf.remove(0);
//閫氱煡鐢熶駭鑰
this.notifyAll();
}
returns;
}
publicstaticvoidmain(String[]args){
//鑷宸卞疄鐜扮殑錛屽畨鍏ㄩ槦鍒
finalTestThread2tt=newTestThread2();
//鐢熶駭鑰
Threadp=newThread(newRunnable(){
@Override
publicvoidrun(){
while(!Thread.currentThread().isInterrupted()){
Randomr=newRandom();
tt.put(String.valueOf(r.nextInt(10)));
}
}
});
//娑堣垂鑰
Threadc1=newThread(newRunnable(){
@Override
publicvoidrun(){
while(!Thread.currentThread().isInterrupted()){
System.out.println("綰跨▼錛"+Thread.currentThread().getId()+"鑾峰彇鍒版暟鎹"+tt.take());
}
}
});
Threadc2=newThread(newRunnable(){
@Override
publicvoidrun(){
while(!Thread.currentThread().isInterrupted()){
System.out.println("綰跨▼錛"+Thread.currentThread().getId()+"鑾峰彇鍒版暟鎹"+tt.take());
}
}
});
p.start();
c1.start();
c2.start();
try{
p.join();
c1.join();
c2.join();
}catch(InterruptedExceptione){
}
}
}