我正在学习Threads。在学习的过程中,我遇到了两个线程使用静态变量的情况。
我想要两个线程之间的同步行为。
这是我的代码:
package com.learning.fizzbuzz;
public class Trigger {
public static void main(String[] args) {
Solution s = new Solution("thread1");
s.start(20);
Solution s1 = new Solution("thread2");
s1.start(15);
}
}
package com.learning.fizzbuzz;
import java.util.ArrayList;
import java.util.List;
public class Solution implements Runnable{
private Thread t;
private String threadName;
private static int n;
public Solution(String threadName) {
this.threadName = threadName;
System.out.println("Creating thread :: "+ threadName);
}
public static List<String> fizzBuzz(int n) {
List<String> elements = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i % (15) == 0) {
elements.add("FizzBuzz");
}
else if (i % 3 == 0) {
elements.add("Fizz");
}
else if (i % 5 == 0) {
elements.add("Buzz");
}
else {
elements.add(String.valueOf(i));
}
}
return elements;
}
public static String reverseString(String s) {
StringBuffer str = new StringBuffer(s);
s = str.reverse().toString();
return s;
}
@Override
public synchronized void run() {
System.out.println("Executing thread :: " + threadName);
List<String> str = fizzBuzz(n);
System.out.println(str +" :: "+ t.getName());
System.out.println(reverseString("Hello") +" :: "+ t.getName());
}
public void start(int num) {
if (t == null) {
System.out.println("Starting thread :: " + threadName);
t = new Thread(this, threadName);
Solution.n = num;
System.out.println("number is " + n);
t.start();
} else {
System.out.println("Thread Already Created and Running :: " + threadName);
}
}
}
我尝试同步Solution类的各个块,但无法获得如下所述的结果。
[1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14, FizzBuzz,16,17,Fizz,19,Buzz] :: thread2 olleH :: thread2
[1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14, FizzBuzz] :: thread1 olleH :: thread1
请告知。
编辑:我观察到的一件事是,在两个线程开始执行之前,n的值设置为15。如何避免?