-1
在這個任務中,我應該有三個線程,這些線程應該從0開始計數,每秒打印一次計數並在7秒和15秒打印消息。多線程時出錯
我找不出我的錯誤,我認爲這是我的線程不知道他們指的是什麼,但我不確定。
錯誤:
Exception in thread "Thread-0" Exception in thread "Thread-1" Exception in thread "Thread-2" java.lang.NullPointerException
at TimePrinter.run(TimePrinter.java:7)
at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
at MessagePrinter2.run(MessagePrinter2.java:8)
at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
at MessagePrinter1.run(MessagePrinter1.java:8)
at java.lang.Thread.run(Unknown Source)
public class Counter{
private int counter;
private Lock counterLock;
private Condition sevenCondition;
private Condition fifteenCondition;
public Counter() {
counter = 0;
counterLock = new ReentrantLock();
sevenCondition = counterLock.newCondition();
fifteenCondition = counterLock.newCondition();
}
public void incrementCounter(){
counterLock.lock();
try{
counter++;
if (counter%7 == 0)
sevenCondition.signal();
//else sevenCondition.await();
if (counter%15 == 0)
fifteenCondition.signal();
//else fifteenCondition.await();
System.out.print(" " + counter + " ");
} finally {counterLock.unlock();}
}
public void sevenSecondMessage()throws InterruptedException{
counterLock.lock();
try{
while (counter%7 != 0){
sevenCondition.await();
System.out.println("Seven Second Message");
}
} finally {counterLock.unlock();}
}
public void fifteenSecondMessage() throws InterruptedException{
counterLock.lock();
try{
while (counter%15 != 0){
fifteenCondition.await();
System.out.println("Fifteen Second Message");
}
} finally {counterLock.unlock();}
}
}
public class TimePrinter implements Runnable{
private Counter counter;
public synchronized void run(){
try {
counter.incrementCounter();
Thread.sleep(1000);
} catch (InterruptedException e){}
}
}
public class MessagePrinter1 implements Runnable{
private Counter counter;
public synchronized void run(){
try {
counter.sevenSecondMessage();
}catch (InterruptedException e){}
}
}
public class MessagePrinter2 implements Runnable{
private Counter counter;
public synchronized void run(){
try {
counter.fifteenSecondMessage();
}catch (InterruptedException e){}
}
}
public class Main2 {
public static void main(String[] args){
Runnable timeprinter = new TimePrinter();
Runnable message1 = new MessagePrinter1();
Runnable message2 = new MessagePrinter2();
new Thread(timeprinter).start();
new Thread(message1).start();
new Thread(message2).start();
}
}
'計數器'不提及任何東西;解決該問題。 – ChiefTwoPencils