【问题标题】:how to Block two threads object accessing 1 method, which is from same class如何阻止两个线程对象访问来自同一类的1个方法
【发布时间】:2016-11-27 12:25:13
【问题描述】:
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();
    }
}

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

【问题讨论】:

    标签: java multithreading concurrency synchronization synchronized


    【解决方案1】:

    您可以将thread.join() 与内联 cmets 一起使用,如下面的代码所示:

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

    A 类代码:

    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

    【讨论】:

      【解决方案2】:

      尝试在类对象上同步

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

      【讨论】:

      • B.class是什么意思?这是否意味着我们必须将其锁定在班级级别? @andrey-cheboksarov
      • @eagle 是的,就是这样。您锁定类对象。使用同步的非静态方法,您可以锁定实例。在您的情况下,实例可以表示 b1 或 b2,但它们是独立的。另一种选择是同步静态方法,它也可以工作
      • 谢谢!我得到了很好的解释! @andrey-cheboksarov
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-20
      相关资源
      最近更新 更多