2

我是多线程的新手,这有点令人困惑。我怎样才能使用同步键给出输出: 1 a 然后 2 b ?换句话说,我希望第一个线程访问静态变量 x,递增它,然后启动第二个线程。

public class Test1 extends Thread{
    static int x=0;
    String name;

    Test1(String n){ name=n;}
    public void increment() {
        x=x+1;
        System.out.println(x+" "+ name);
    }

    public void run() {
        this.increment();
    }   
}
public class Main {
    public static void main(String args[]) {
        Test1 a= new Test1("a");
        Test1 b= new Test1("b");
        a.start();
        b.start();
    }
}
4

2 回答 2

0

您可以使用同步静态方法(increment无论如何您只是在静态字段上进行操作,那么为什么不将其设为静态?)。

public static synchronized void increment() {
    x=x+1;
    System.out.println(x+" "+ name);
}

这种方法在整个类对象上同步。

如果您出于某种原因确实不想使此方法成为静态方法,则可以显式地同步类对象上的关键部分

public void increment() {
    synchronized(Test1.class) {
        x=x+1;
        System.out.println(x+" "+ name);
    }
}
于 2019-10-22T21:19:18.407 回答
0

我建议使用 AtomicInteger 并调用 incrementAndGet()。这将自动递增变量,并防止其他线程返回对该变量的调用,直到前面的锁被删除,所以你的递增方法是:

System.out.println(x.incrementAndGet()+" "+ name);

您也可以使用其他用户发布的同步块,但是这两个建议的缺点是您牺牲了对锁定对象的控制,因为方法上的同步关键字等效于:

synchronized (this) { }

并且引用类对象不会将对象保留在类内部。

于 2019-10-22T21:26:25.340 回答