0

I have a problem to get two threads working on the same array. So far I am not concerned about the synchronisation because I do not get them operating on the same array.

I tried three approaches so far. (I think of the execution of the main function as a thread, so in the code samples I will only create 1 thread).

1) I create an array inside the main function, but when I try to tell the thread inside its run() function to manipulate the array in the main function it says the array I am refering to can not be resolved to a variable.(dont worry about allZero(),noZero(),writeZero(),writeOne(). This code is solely written for this post in order to focus on my real problem: How to get two threads work on the same array?)

public class StackOverflow1 implements Runnable {


public static void main(String[] args) {
    int a[]={0,0,0,0,0,0,0,0,0,0};

    Thread thread= new Thread(new StackOverflow1());
    thread.start();

    while(true){
        if(!allZero(a)){
            writeZero(a);
        }
    }

}

@Override
public void run() {
    while(true){
        if(!noZero(a)){
            writeOne(a);
        }

    }

}

}

2) So, I create an array as part of the class that determines the thread. Now the problem is, when I want to manipulate the array inside the main function it says that it can not make static reference to a non static field.

public class StackOverflow2 implements Runnable {

int []a={0,0,0,0,0,0,0,0,0,0};

public static void main(String[] args) {
    Thread thread= new Thread(new StackOverflow2());
    thread.start();

    while(true){
        if(!allZero(a)){
            writeZero(a);
        }
    }

}

@Override
public void run() {
    while(true){
        if(!noZero(a)){
            writeOne();
        }

    }

}

}

3) If I create two instances of a thread which both have an array as part of their class, then I have just two threads both operating on their own array. How can I get two threads operating on the same array? Thank you for your help

Edit: I will describe my current situation a bit more detailed. In about three weeks I have to write an exam about simulation. The exam will not contain a single code line. It will be all about statistics (problems on maximum likelihood estimators and chi^2 tests) and probability theory. But a key model of the lecture are M/M/x queues. I am not a coder. Coding is not my hobby. Therefore I will miss many implications of statements being made in books or here on Stack Overflow.

All I want is to get some intuition for M/M/x queues by using my little coding skill (I am not even using a queue. It is an array of fixed length) in order to prepare my brain to learn the theory that is contained in the lectures and tutorials. Does this make sense? So my problem (the exam) is already split into many sub-problems and all I was asking here is help for one of my nuggets. To be fair the original question hides my situation.

halfer
  • 19,824
  • 17
  • 99
  • 186
Heilmann
  • 67
  • 1
  • 9
  • You should have a look at basic concepts first. `a` in your first code snippet is not in the scope of the Thread's run() method. It does not "see" `a`. If you make a class variable, it is not static and cannot be referenced from main(). That's (not) working as expected. So I would recommend some reading on Variable scope ... – Fildor Sep 14 '15 at 14:08
  • Hi there. I've edited out a large chunk of commentary about the Stack Overflow process, which does not belong in the question, but I can try to answer your points briefly. – halfer Sep 15 '15 at 08:27
  • You've complained that answers are often supplied as hints rather than full solutions that can be typed in verbatim. We get both kinds here, but I am very supportive of people who give partial answers. The purpose is to help people learn, and there is a view here that if a full answer is given, the original poster may not learn anything. – halfer Sep 15 '15 at 08:30
  • You also mentioned that responses should be treated as "time-sensitive" because the questioner spent time preparing a post and they may be under a deadline. This is not a correct assumption. As far as I know, everyone who answers here does so in their free time, mainly for fun, or to learn something, or perhaps to polish their professional resume. No-one has any obligation to answer here, and no-one answering is under any pressure to answer within a certain time frame. We often get questions marked as "urgent", and they sometimes get downvoted rather quickly. – halfer Sep 15 '15 at 08:35

2 Answers2

1

1) In this case, the array is a local variable in the main() method, it's not accessible outside of the main method.

2) Main is static (ie. it's not bound to an instance of StackOverflow2), and the array is an instance variable. Since there is no object instance in main (static method), you cannot access any of its instance variables. You could fix it by making the array static (ie. shared among all StackOverflow2 instances) but probably it's not what you are after.

3)You can create the array in main, and pass it as a an argument to StackOverflow2's constructor. Then you will have to think about synchronising access to the shared array.

alampada
  • 2,329
  • 1
  • 23
  • 18
0

To access a local variable from another thread, declare it final:

final int a[]={0,0,0,0,0,0,0,0,0,0};

Here is a short example:

public class FinalLocalArray {

public static void main(String[] args) {
    final int a[]={0,0,0,0,0,0,0,0,0,0};

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            a[0] = 1;
        }
    });
    t.start();

    try {
        t.join();
    } catch (InterruptedException e) {
    }

    a[2] = 1;

    System.out.println(Arrays.toString(a));

}

}

dimplex
  • 494
  • 5
  • 9
  • It is never possible for one thread to access a local variable of another thread. An anonymous inner class may _appear_ to use to a `final` local from an enclosing scope, but it's smoke and mirrors. What really happens; The inner class has an implicit, final _instance_ variable with the same name, and it has an implicit constructor arg that is supplied by the local var when the inner object is created. That's why it only works for `final` locals: If you were allowed to update the value of the local, the value of the inner-class field would not change, and the illusion would be destroyed. – Solomon Slow Sep 14 '15 at 17:55
  • Added an example to my answer. In this particular case the local variable is an array, so a reference is copied to the inner class, thus making the array accessible as shown in the example. The anonymous inner Runnable is operated by another thread. – dimplex Sep 15 '15 at 07:14