【问题标题】:Java multi-threading synchronization [duplicate]Java多线程同步[重复]
【发布时间】:2017-11-04 14:50:22
【问题描述】:

我正在学习java中的同步。今天被下面的示例代码打动了。

在下面的代码中,test() 方法是同步的。所以,我假设 th1test() 调用将完成,然后 th2test() 调用会开始。然而,事情并不是这样发生的。输出交织在一起。你能帮我理解为什么吗?

public class MyThread {

    public static void main(String[] args) 
    {
        SampleThread sample = new SampleThread("one");
        Thread th = new Thread(sample);
        th.start();

        SampleThread sample2 = new SampleThread("two");
        Thread th2 = new Thread(sample2);
        th2.start();
    }
}



class SampleThread implements Runnable
{

    public SampleThread(String name)
    {
        this.name=name;
    }

    String name;


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

    public synchronized void test()
    {
        for(int j=0;j<10;j++)
        {
            System.out.println(name + "--" + j );
        }
    }

}

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

    要同步线程,您需要公共点来同步它们。创建对象,将其传递给线程,然后您可以在对象上syncronize。如果您需要在第一个线程中的对象上wait,并在第二个线程中notifyFirst example 来自谷歌。

    【讨论】:

      【解决方案2】:

      方法 test() 是同步的,但它不会被多个线程调用,因为每个线程都有一个不同的 SampleThread 实例。对两个线程使用单个 SampleThread 以获得后续输出。

      public class MyThread {
      
        public static void main(String[] args) {
          final SampleThread sample = new SampleThread();
      
          Thread th = new Thread(sample);
          th.start();
      
          Thread th2 = new Thread(sample);
          th2.start();
        }
      }
      
      
      class SampleThread implements Runnable {
        @Override
        public void run() {
          test();
        }
      
        public synchronized void test() {
          for (int j = 0; j < 10; j++) {
            System.out.println(Thread.currentThread().getId() + "--" + j);
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-07-25
        • 1970-01-01
        • 2012-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多