当前位置:首页 » 编程语言 » java多线程练习题

java多线程练习题

发布时间: 2025-01-23 19:01:27

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){
}


}

}
热点内容
养猫用什么配置 发布:2025-01-24 00:37:58 浏览:811
pythongps 发布:2025-01-24 00:37:51 浏览:812
办公编程鼠标 发布:2025-01-24 00:37:07 浏览:385
wpa加密类型 发布:2025-01-24 00:35:58 浏览:959
如何用批处理实现ftp映射盘符 发布:2025-01-24 00:25:45 浏览:953
win7sql版本 发布:2025-01-24 00:22:16 浏览:498
安卓手机市场有什么 发布:2025-01-23 23:48:56 浏览:25
银城医考能缓存的视频 发布:2025-01-23 23:44:51 浏览:542
智能电视linux 发布:2025-01-23 23:42:54 浏览:843
ncg密码是什么意思 发布:2025-01-23 23:36:09 浏览:82