in my program I need to have multiple threads use and edit the same variable, but it doesn't seem to be working. Here is an example of what I mean, this 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 would 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 on the spot, so there may be some errors, but thats ok. My program basically needs to do something like this, but instead of printing the number plus 1 every time, all the threads simply print the same number, 0, multiple times. Please help me, thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…