in my program, I need to use multiple threads and edit the same variable, but it does not seem to work. Here is an example of what I mean, it would be my main class.
public class MainClass { public static int number = 0; public static String num = Integer.toString(number); public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter number of threads."); int threads = in.nextInt(); for (int n = 1; n <= threads; n++) { java.lang.Thread t = new Thread(); t.start(); } } }
This will be my Thread class:
public class Thread extends java.lang.Thread { public void run() { MainClass.number++; System.out.println("Thread started"); System.out.println(MainClass.num); } }
I wrote this code in place, so there may be some errors, but this is normal. My program should basically do something like this, but instead of printing the number plus 1 each time, all threads just print the same number 0, several times. Please help me, thanks.
source share