1

Hey I'm trying to grasp Threads as a concept. Let me draw you a scenario

class A {
    private int counter = 0;

    public void add() {
        counter++;
    }

    public int getCounter() {
        return counter;
    } 
}

class B implements Runnable {
    public void run() {
        A a = new A();
        a.add();
        a.add();
    }
}

class C implements Runnable {
    public void run() {
        A a = new A();
        System.out.println(a.getCounter());
    }
}

What does the System.out.println give me when I run C? I'm guessing it gives me 0 because they each created an instance of A.

If thats true, how would you share that object between the threads?

1
  • 2
    Would you please format your example correctly! It doesn't even compile. Commented Nov 25, 2013 at 17:43

2 Answers 2

2

You wouldn't see anything on System.out, because you don't have a complete program. But, assuming you created two threads, and ran B with one, then ran C with the other, yes, 0 would be printed, because as you surmise, each thread uses a separate instance of A. And that's good, because A doesn't have any memory barriers that would allow it to be accessed safely by multiple threads.

To share data, you'd pass one object to both threads. For example:

final class Test {

  public static void main(String[] argv) throws InterruptedException {
    AtomicInteger shared = new AtomicInteger();
    Thread a = new B(shared).start();
    a.join();
    Thread b = new C(shared).start();
    b.join();
  }

}

final class B extends Thread {

  private final AtomicInteger shared;

  B(AtomicInteger shared) { this.shared = shared; }

  @Override()
  public void run() {
    shared.getAndIncrement();
    shared.getAndIncrement();
  }

}

final class C extends Thread {

  private final AtomicInteger shared;

  C(AtomicInteger shared) { this.shared = shared; }

  @Override()
  public void run() {
    System.out.println(shared.get());
  }

}

This will print 2, because the main method is ensuring that the threads run sequentially. In a more realistic approach, the threads would be started at the same time, and 0, 1, or 2 would be printed depending on the relative timing.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm sorry about my code it was meant a little as pseudo I thought it was clear enough waht I meant with it. But then I understand it correctly that if each class creates an Object they wouldn't be working with the same int. you say passing the object, are there alternatives?
Thank you for your answer It was clear to me, but i think I will rely on passing of objects atm.
@AllanPedersen The important thing is that the object shared between threads must be safe for concurrent access. That means not only should multiple modifications to the shared object appear to be atomic, but that a memory barrier guarantees that changes are visible to other threads. It's safer to use immutable objects, or to use a concurrent queue to explicitly pass objects from one thread to another at identified points, rather than having one object that can be modified asynchronously at any point.
1

What you see in the console (assuming something instantiates C and passes it to a thread that executes it) will be 0, because nothing else is writing to that instance of A. a is a local variable of the run method, nothing else can see it.

Multithreaded access is when objects get passed around between threads. One typical example is a queue, where you have different threads writing to a data structure, and other threads removing objects from the same data structure. Each thread writing to the queue (a producer) would create objects and put them in the queue. The same objects would be retrieved by different threads (called consumers) that are dedicated to taking objects from the queue and doing something with them. So an object created by a producer gets placed in the queue and stays there until it gets taken by a consumer.

Here's a simple queue implementation. It uses synchronized to lock on the internal list so that only one thread at a time gets access to the queue.

public class MyQueue<T> {

    private List<T> list = new ArrayList<T>();

    public T take() throws InterruptedException  {
        synchronized(list) {
            while (list.size() == 0) {
                list.wait();
            }
            return list.remove(0);
        }
    }

    public void put(T object) {
        synchronized(list) {
            list.add(object);
            list.notifyAll();
        }
    }
}

1 Comment

This should be the accepted answer. Queues are most certainly what OP is referring to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.