gpt4 book ai didi

java - 调用静态和非静态方法的线程

转载 作者:行者123 更新时间:2023-11-29 07:12:02 25 4
gpt4 key购买 nike

免责声明:此代码复制自 synchronized blocks for static and non-static methods

我对它做了一些修改。我想知道如何让线程同时调用同步 静态和非静态方法。我可以通过将非静态方法包装在 synchronized block 中使其工作。还有其他办法吗?

public class StaticNonStaticSynch  
{
public static void main(String[] args)
{
final StaticNonStaticTest staticNonStaticTest = new StaticNonStaticTest();
Runnable runnable1 = new Runnable()
{
@Override
public void run()
{
staticNonStaticTest.nonStaticMethod();
}
};

Runnable runnable2 = new Runnable()
{
@Override
public void run()
{
StaticNonStaticTest.staticMethod();
}
};

Thread thread1 = new Thread(runnable1, "First Thread");
Thread thread2 = new Thread(runnable2, "Second Thread");

thread1.start();
thread2.start();
}
}

class StaticNonStaticTest
{

void nonStaticMethod()
{
//synchronized (StaticNonStaticTest.class){
for(int i=0;i<50;i++)
{
System.out.println("Non - Static method called by " + Thread.currentThread().getName() +" : = "+i);
}
// }
}
static synchronized void staticMethod()
{
for(int i=0;i<50;i++)
{
System.out.println("Static method called by " + Thread.currentThread().getName() +" : = "+i);
}
}
}

最佳答案

请记住:

public class MyClass {

public synchronized void doSomething() {
// Do something
}

public synchronized static void doSomethingStatic() {
// Do something static
}
}

基本上编译成这样:

public class MyClass {

public void doSomething() {
synchronized(this) {
// Do something
}
}

public static void doSomethingStatic() {
synchronized(MyClass.class) {
// Do something static
}
}
}

请注意,它们不会在同一事物上同步。要解决此问题,请为它们创建一个对象以锁定(称为互斥对象或“互斥对象”):

public class MyClass {

private static final Object MUTEX = new Object();

public void doSomething() {
synchronized(MUTEX) {
// Do something
}
}

public static void doSomethingStatic() {
synchronized(MUTEX) {
// Do something static
}
}
}

这应该使得这两个方法中只有一个在多个线程中同时运行。

一些提示:

  • 始终对finalvariable 使用synchronized(variable)
  • MUTEX 不一定是严格意义上的互斥锁,它可以是一个实际的对象。请参阅下面的示例。
  • 记住方法上的 synchronized 修饰符是如何有效实现的。它就像 thisMyClass.class 上的 synchronized block 。

除了拥有严格意义上的互斥锁对象外,您还可以使用任何final 字段。例如,在 Map 上同步在迭代期间:

public class MyClass {

private static final Map<String, String> map = new HashMap<String, String>(); // Java 6
private static final Map<String, String> map = new HashMap<>(); // Java 7

public static void put(String k, String v) {
synchronized(map) {
map.put(k, v);
}
}

public static void printAll() {
synchronized(map) {
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
}

这段代码保证你永远不会得到 ConcurrentModificationException

关于java - 调用静态和非静态方法的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13058801/

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