简体   繁体   English

Java中的线程同步/生产者-消费者。 重复打印数字1-10,然后再打印10-1

[英]Thread synchronization/producer-consumer in java. Printing out numbers 1-10 then 10-1 repeatedly

I'm very new to java and found an exercise to work on basic thread synchronization. 我对Java非常陌生,并且发现了一个可以进行基本线程同步的练习。 The problem is to print out 12345678910 10987654321 repeatedly until the program stops. 问题是反复打印出12345678910 10987654321,直到程序停止。 Ten different threads should be used. 应该使用十个不同的线程。

This is my code so far: I am first working on trying to get just the first number (number one to work), but it keeps giving me an exception 到目前为止,这是我的代码:我正在首先尝试仅获取第一个数字(起作用的数字),但是它一直给我一个例外

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");
        }
    }
}

I may be going about this the completely wrong way, but I've read a lot of documentation and am just thoroughly confused. 我可能会以完全错误的方式进行此操作,但是我已经阅读了很多文档,并且感到非常困惑。

It looks like you didnt create a new instance of update 看来您没有创建更新的新实例

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");
        }
    }
}

// you need to alocate memory to updateNumber like this //您需要像这样将内存分配给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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM