Java 同步类的成员变量
我正在学习线程。在学习过程中,我遇到了一个场景,其中一个静态变量由两个线程使用 我想要两个线程之间的同步行为 这是我的密码:Java 同步类的成员变量,java,multithreading,Java,Multithreading,我正在学习线程。在学习过程中,我遇到了一个场景,其中一个静态变量由两个线程使用 我想要两个线程之间的同步行为 这是我的密码: package com.learning.fizzbuzz; public class Trigger { public static void main(String[] args) { Solution s = new Solution("thread1"); s.start(20); Solution
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);
}
}
}
package com.learning.fizzbuzz;
公共类触发器{
公共静态void main(字符串[]args){
溶液s=新溶液(“螺纹1”);
s、 启动(20);
溶液s1=新溶液(“螺纹2”);
s1.启动(15);
}
}
包com.learning.fizzbuzz;
导入java.util.ArrayList;
导入java.util.List;
公共类解决方案实现可运行{
私有线程t;
私有字符串threadName;
私有静态int n;
公共解决方案(字符串threadName){
this.threadName=threadName;
System.out.println(“创建线程::”+threadName);
}
公共静态列表fizzBuzz(int n){
列表元素=新的ArrayList();
对于(int i=1;i要访问静态共享变量,需要同步同一监视器上的两个(或多个)线程
无法在方法实例上使用关键字synchronized
,因为它在变量This
上同步
最简单的方法是使用静态变量进行同步
public class MyClass {
private static Object lock = new Object();
private static int sharedVariable;
public void yourMethod() {
synchronized(lock) {
// Do something with sharedVariable
}
}
}
您想要的行为到底是什么?第一个线程应该在数组中打印20个元素。第二个线程应该在数组中打印15个元素。您应该使用一个实例变量来获得该结果。@tushar从n
中删除static
修饰符。然后两个解决方案
都有自己的值,而不是使用相同的值。@tushar使用静态变量时,首先将其设置为20,然后将其更改为15。在第一个线程访问它之前,可能会发生这种情况,也可能不会发生这种情况。使用非静态变量,两个实例都有自己的值;20和15将存储在不同的内存位置。它确实有效,但不适用于您尝试执行的操作。这里的“同步”意味着只有一个线程可以在同步块中输入和执行代码。但是,即使这样做,您仍然有一个变量要保存两个单独的值。