Create a new console for each thread in java

Viewed 457

I want to create a multithread application, each thread represent a console and share common resources. Staring from a loop menu and a dummy resource

public class Resource {
    int id;
    public Resource(int id) {
        this.id = id;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
}

Menu

        int choiceentry;
        Scanner scanchoice = new Scanner(System.in);
        Resource r = new Resource(10);
       //create 2 threads both having a console with menu and acces to the same resource r
        do {
            System.out.print("1.Get resource\n2.Set resource to random\n\n");
            System.out.print("Enter your option: ");
            choiceentry = scanchoice.nextInt();
            switch (choiceentry) {
            //get the resource id
                case 1:
                System.out.println("Resource get: " + r.getId());
                break;
           //set the resource id
            case 2:
                Random rand = new Random();
                int newId = rand.nextInt(10);
                r.setId(newId);
                System.out.println("Resource set to: " + newId);
                
                break;
            case 4:
                System.exit(0);
            default:
                System.out.println("Choice must be a value between 1 and 3.");
            }
            System.out.print("\n\n");
        } while (true);

Is it possible to start 2 consoles that using the menu to access the same resource r ?

1 Answers

Is it possible to start 2 consoles.

No. Not without firing up an entirely now java.exe which is probably not what you want to do (that's a lot more complicated than writing some basic swing stuff to create 2 GUI windows).

to access the same resource r

Also no. You can't access the same object from different threads unless you write code that controls how changes to this object made from one are synced up to the other. You haven't shown any such code, which means you get this particularly nasty result: Whether any change made in thread 1 is visible in thread 2 is arbitrary: Right now it's visible, tomorrow it isn't. On your computer it always works, on client computer it usually works it fails right when you are giving that important demo.

Multithreaded code that needs to share state is quite complicated. There's a reason most people run such comms through a DB :)

Related