如何阻止两个线程对象访问来自同一个 class 的 1 个方法

how to Block two threads object accessing 1 method, which is from same class

public class B extends Thread {

    @Override
    public void run() {
        print();
    }

    public synchronized void print(){
    int i;
        for (i=0;i<1000;i++){
        System.out.println(Thread.currentThread().getName() );
        }
    }

}

public class A {
    public static void main(String[] args) {
        B b1=new B();
        B b2=new B();

        b1.start();
        b2.start();
    }
}

如何锁定访问 class B 的两个对象的打印方法?我想要的是这里我已经同步了没有用的方法!所以我希望线程 1 到 运行 打印方法 1st 然后是线程 2。我怎样才能更改代码?

尝试在 class 对象上同步

public void print(){
    synchronized(B.class) {
         int i;
         for (i=0;i<1000;i++) {
             System.out.println(Thread.currentThread().getName() );
         }
    }
}

您可以使用 thread.join(),如下面的代码所示,带有内联注释:

class B码:

public class B extends Thread {

        @Override
        public void run() {
            print();
        }

        //Remove synchronized
        public void print(){
            int i;
            for (i=0;i<1000;i++){
                System.out.println(Thread.currentThread().getName());
            }
        }
    }

class一个码:

public class A {

    public static void main(String[] args) throws Exception {
            B b1=new B();
            B b2=new B();

            b1.start();//start first thread

            b1.join();//Use join, to let first thread complete its run()

            b2.start();//run second thread
      }
 }

此外,作为旁注,我建议您使用 class B implements Runnable 而不是扩展 Thread