導航:首頁 > 編程語言 > java多線程習題

java多線程習題

發布時間:2025-08-05 01:13:45

『壹』 基礎java題 試編寫一個多線程的程序:啟動4個線程。其中兩個循環10次,每次將某全局變數加1,另兩個循環1

publicclassDay18_A{
publicstaticvoidmain(String[]args)throwsInterruptedException{
Recounrec=Recoun.getRec();
Thread[]trr=newThread[4];
for(inti=0;i<4;i++){
trr[i]=newThread(newNumberTest(rec,i),"線程"+(i+1)+": ");
}
for(Threadthread:trr){
thread.start();
}
for(Threadthread:trr){
thread.join();
}
System.out.println("所有線程結束查看結果:"+rec.getCount());
}
}

{
privateRecounre;
privateintn;
NumberTest(Recounr,inti){
this.re=r;
this.n=i;
}
publicvoidrun(){
for(inti=0;i<10;i++){
re.method(n);
}
}
}
classRecoun{
privateintcount=0;
privateRecoun(){
}
privatestaticfinalRecounrec=newRecoun();
publicstaticRecoungetRec(){
returnrec;
}
publicsynchronizedvoidmethod(inti){
if(i%2==0){
System.out.println(Thread.currentThread().getName()+(count++));
}else{
System.out.println(Thread.currentThread().getName()+(count--));
}
}
publicsynchronizedintgetCount(){
returncount;
}
}

『貳』 課程設計題目,多線程編程:醫院門診模擬,想用java實現,求大神指點

典型的生產者消費者模型。

了解j5的並發庫,那個並發庫中有適合組件實現。

如果不了解,這么來:

創建一個隊列,此隊列要求線程安全,如果隊列為空則消費者阻塞。如果隊列達到某個最大值,則阻塞生產者。

隊列用,普通的list或實現好的隊列包裝成線程安全的。

用synchronized同步原方法或代碼塊。

寫一個或n個線程,模擬病人,排隊辦理業務,往上面的隊列中添加數據。

當達到隊列的最大容積,阻塞,等待生產者線程取數據。

阻塞:makerLock.wait();//虛擬機會出讓線程掛起,其實就是操作系統,保存當前線程在cpu上的運行狀態。再出讓線程正在使用的cpu資源,佔用的內存不會釋放。

往隊列插入數據的時候,因為不知道是否有消費者處於等待狀態,通知消費者:

customerLock.notifyAll();//虛擬機調度消費者線程運行,實際上是操作系統,把保存的消費者線程狀態,從新載入到cpu中接著運行。接著運行線程是任意的,取決於不同操作系統的線程調度演算法

消費者線程讀取一個數據後,要通知生產者,可以繼續,道理同上:

makerLock.notifyAll();

隊列中,無數據可讀的時候:

customerLock.wait();//原理同上,

最後注意,生產者跟消費者使用了兩個不同的對象鎖。lock.wait()的使用方法是這樣的:

synchronized(lock){

......

while(condition==true){

lock.wait();

}

......

Objecto=queen.pop();

lock.notifyAll();

}

最後啟動n個線程讀隊列,模擬辦理業務的窗口;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){
}


}

}

『叄』 java 用多線程模擬龜兔賽跑:

public class TortoiseAndHareRace {
public static void main(String[] args) {
Runnable vs=new Race();
Thread hare=new Thread(vs,"Hare");
Thread tortoise =new Thread(vs,"Tortoise");
System.out.println("Ready!GO!");
hare.start();
tortoise.start();
}
}
class Race implements Runnable{
private static final int S=1000;
@Override
public void run() {
if(Thread.currentThread().getName().equals("Hare")){
int sHare=0;
while(sHare<=S){
sHare+=5;
if(sHare%20==0)
try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
}
}else{
int sTortoise=0;
while(sTortoise<=S){
sTortoise++;
if(sTortoise%100==0)
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

『肆』 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採用實現Runnable介面的多線程技術,用50個線程,生成10000個[1-1000]間的隨機整數。

Java利用實現Runnable介面的多線程技術生成大量隨機數,具體案例中,定義了一個名為RandomNumber的類,實現了Runnable介面,用於生成隨機數。該類包含一個鎖對象lock,用於同步處理,一個Random對象用於生成隨機數,以及一個整數sum,用於記錄生成的隨機數總數。

RandomNumber類的構造函數初始化了鎖對象和Random對象。其run方法實現多線程並發生成隨機數,使用while循環,循環中首先生成一個0到1000之間的隨機數。當生成的隨機數等於0時,繼續循環;否則,如果sum已經達到10000,則結束循環。

為了使程序運行效果更明顯,run方法中加入了一個1毫秒的延時操作。接著,使用synchronized關鍵字確保在更新sum值時的線程安全,通過判斷sum是否小於10000來決定是否繼續生成隨機數。當滿足條件時,將sum值加1,並輸出當前線程名和生成的隨機數。

在main方法中,創建了一個RandomNumber實例,並啟動50個線程,每個線程都執行RandomNumber的run方法,從而並發生成隨機數。

這種多線程技術的應用,不僅能夠提高程序的執行效率,還能幫助理解Java中線程同步的概念和實現方式。通過這種方式,每個線程都能獨立地生成隨機數,並通過鎖對象確保了多線程環境下的數據一致性。

在實際開發中,這種技術常用於需要大量並發處理的任務,如網路請求、文件讀寫等場景,能夠顯著提升程序的處理能力和用戶體驗。

值得注意的是,雖然通過線程並發可以提高效率,但也需要關注線程之間的協調和資源競爭問題,避免產生死鎖或資源競爭等並發編程中的常見問題。

閱讀全文

與java多線程習題相關的資料

熱點內容
androidmainxml 瀏覽:109
des可逆加密演算法 瀏覽:249
aix查看系統信息常用命令 瀏覽:154
phpmemcache實例 瀏覽:249
爆槍源碼 瀏覽:566
編程大佬能記住所有代碼 瀏覽:858
如何批量注冊國家反詐app 瀏覽:526
實現ping命令 瀏覽:19
cmd進入管理員命令 瀏覽:479
pdf在線編輯修改 瀏覽:967
文件夾是只讀是什麼意思 瀏覽:88
伺服器如何知道訪問域名 瀏覽:319
java網路編程實驗總結 瀏覽:85
linux下dns伺服器配置 瀏覽:707
我的命令是絕對的 瀏覽:932
助飛器app在哪裡下 瀏覽:64
無廣告win10解壓縮 瀏覽:476
台灣的伺服器怎麼選雲伺服器 瀏覽:813
群暉媒體伺服器平板上怎麼看 瀏覽:625
pdf文件怎麼轉換成jpg格式 瀏覽:724