如何用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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 适用于ABAQUS的黏弹性边界(粘弹性边
- 下一篇: 在物联网领域,英特尔除了高速计算的芯片,