gpt4 book ai didi

java - 同步类的成员变量

转载 作者:行者123 更新时间:2023-12-03 13:09:22 27 4
gpt4 key购买 nike

我正在学习线程。在学习的过程中,我遇到了一个场景,其中两个线程使用一个静态变量。

我想要两个线程之间的同步行为。

这是我的代码:

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);
}
}
}

我尝试同步解决方案类的各个块,但无法获得如下所述的结果。

[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。如何避免呢?

最佳答案

要访问静态共享变量,您需要在同一监视器上同步两个(或多个)线程。

在方法实例上使用关键字synchronized不能完成此操作,因为它在变量this上同步。

最简单的方法是使用静态变量进行同步。

public class MyClass {
private static Object lock = new Object();

private static int sharedVariable;

public void yourMethod() {

synchronized(lock) {
// Do something with sharedVariable
}
}

}

关于java - 同步类的成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41065248/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com