温馨提示×

java多线程怎么对公共变量赋值

小亿
113
2023-10-24 22:47:17
栏目: 编程语言

在Java多线程中,可以使用synchronized关键字来实现对公共变量的赋值。

首先,需要定义一个共享的变量,多个线程都可以修改该变量的值。例如:

public class SharedVariable {
    private int value;

    public synchronized void setValue(int newValue) {
        this.value = newValue;
    }

    public synchronized int getValue() {
        return value;
    }
}

在上述代码中,使用synchronized关键字修饰了setValue和getValue方法,确保了在多线程环境下对value变量的读写操作是原子性的。

然后,可以创建多个线程来修改共享变量的值。例如:

public class Main {
    public static void main(String[] args) {
        SharedVariable sharedVariable = new SharedVariable();

        Thread thread1 = new Thread(() -> {
            sharedVariable.setValue(10);
        });

        Thread thread2 = new Thread(() -> {
            sharedVariable.setValue(20);
        });

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

        // 等待线程执行完成
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        int value = sharedVariable.getValue();
        System.out.println("value: " + value);
    }
}

在上述代码中,创建了两个线程thread1和thread2来修改共享变量sharedVariable的值。使用join方法等待线程执行完成后,再打印共享变量的值。

需要注意的是,使用synchronized关键字会带来性能的损耗,因此在实际应用中,可以根据具体的需求选择其他的线程同步机制,如使用Lock对象、使用volatile关键字等。

0