日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

如何用java打印1-100_在java中使用10个线程打印1到100

發布時間:2023/12/20 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何用java打印1-100_在java中使用10个线程打印1到100 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我是多線程的新手,我得到了一個問題,使用

Java中的10個線程以低于約束打印1到100.

>線程t1應打印:

1, 11, 21, 31, … 91

t2應打印:

2, 12, 22, 32, … 92

同樣

t10應打印:

10, 20, 30, … 100

>最終的輸出應該是

1 2 3 .. 100

我試過了,但它在所有10個線程中拋出以下異常:

java.lang.IllegalMonitorStateException

at java.lang.Object.wait(Native Method)

at java.lang.Object.wait(Object.java:485)

at thread.run(MyThread.java:58)

at java.lang.Thread.run(Unknown Source)

請讓我知道如何解決這個問題.

public class MyThread {

/**

* @param args

*/

public static void main(String[] args) {

thread.setSequence();

for(int i = 1; i <= 10; i++) {

Thread t = new Thread(new thread(i));

t.setName(i + "");

t.start();

}

}

}

class thread implements Runnable {

private static HashMap< String, String> sequence = new HashMap();

public static final Object lock = new Object();

public static String turn = "1";

private int startValue = 0;

private AtomicInteger counter = new AtomicInteger(1);

public thread(int startValue){

this.startValue = startValue;

}

@Override

public void run() {

while (!counter.equals(10)){

synchronized (lock) {

if(Thread.currentThread().getName().equals(turn)){

System.out.print(startValue + " ");

startValue += 10;

counter.incrementAndGet();

turn = getNextTurn(turn);

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

else{

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

this.notifyAll();

}

}

}

public static void setSequence(){

for (int i = 1; i <= 10; i++)

if (i == 10)

sequence.put(i + "", 1 + "");

else

sequence.put(i + "", (i + 1) + "");

}

public static String getNextTurn(String currentTurn){

return sequence.get(currentTurn);

}

}

總結

以上是生活随笔為你收集整理的如何用java打印1-100_在java中使用10个线程打印1到100的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。