[英]Thread synchronization/producer-consumer in java. Printing out numbers 1-10 then 10-1 repeatedly
我对Java非常陌生,并且发现了一个可以进行基本线程同步的练习。 问题是反复打印出12345678910 10987654321,直到程序停止。 应该使用十个不同的线程。
到目前为止,这是我的代码:我正在首先尝试仅获取第一个数字(起作用的数字),但是它一直给我一个例外
public static void main(String[] args){
threadOne one = new threadOne();
one.start();
}
}
class updateNumber{
private int i;
synchronized void increase(int s){
this.i=s;
System.out.println(i);
}
}
class threadOne extends Thread {
private updateNumber grab;
public void run() {
try{
grab.increase(1);
}
catch(Exception e){
System.out.println("error in thread one");
}
}
}
我可能会以完全错误的方式进行此操作,但是我已经阅读了很多文档,并且感到非常困惑。
看来您没有创建更新的新实例
class threadOne extends Thread {
private updateNumber grab;
public void run() {
try{
grab.increase(1); // null pointer reference...<<<<<<<
}
catch(Exception e){
System.out.println("error in thread one");
}
}
}
//您需要像这样将内存分配给updateNumber
//private updateNumber grab = new updateNumber();
class threadOne extends Thread {
private updateNumber grab = new updateNumber();
public void run() {
try{
grab.increase(1);
}
catch(Exception e){
System.out.println("error in thread one");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.