【问题标题】:How to chose whether to synchronize an object or a method如何选择是同步对象还是方法
【发布时间】:2018-11-09 09:01:51
【问题描述】:

我在 Internet 上找到了这个同步示例,但我真的不明白在这个特定示例中同步对象和方法之间有什么区别。这里同步在对象发送者上;是否可以同步方法发送并获得相同的结果?

// A Java program to demonstrate working of 
// synchronized. 
import java.io.*; 
import java.util.*; 

// A Class used to send a message 
class Sender 
{ 
    public void send(String msg) 
    { 
        System.out.println("Sending\t"  + msg ); 
        try
        { 
            Thread.sleep(1000); 
        } 
        catch (Exception e) 
        { 
            System.out.println("Thread  interrupted."); 
        } 
        System.out.println("\n" + msg + "Sent"); 
    } 
} 

// Class for send a message using Threads 
class ThreadedSend extends Thread 
{ 
    private String msg; 
    private Thread t; 
    Sender  sender; 

    // Recieves a message object and a string 
    // message to be sent 
    ThreadedSend(String m,  Sender obj) 
    { 
        msg = m; 
        sender = obj; 
    } 

    public void run() 
    { 
        // Only one thread can send a message 
        // at a time. 
        synchronized(sender) 
        { 
            // synchronizing the snd object 
            sender.send(msg); 
        } 
    } 
} 

// Driver class 
class SyncDemo 
{ 
    public static void main(String args[]) 
    { 
        Sender snd = new Sender(); 
        ThreadedSend S1 = 
            new ThreadedSend( " Hi " , snd ); 
        ThreadedSend S2 = 
            new ThreadedSend( " Bye " , snd ); 

        // Start two threads of ThreadedSend type 
        S1.start(); 
        S2.start(); 

        // wait for threads to end 
        try
        { 
            S1.join(); 
            S2.join(); 
        } 
        catch(Exception e) 
        { 
             System.out.println("Interrupted"); 
        } 
    } 
} 

【问题讨论】:

  • 在这种情况下,访问sender 对象将不是线程安全的。
  • 但是在这种情况下sender对象只实现了1个方法,所以是一样的吧?
  • 没错!

标签: java multithreading concurrency synchronization


【解决方案1】:

在您的示例中,在对象上同步和将发送方法声明为 synchronized 之间并没有真正的区别。

但总的来说,在对象上同步的优点是:

  1. 调用者可以选择是否同步。
  2. 调用者可以在同步块中放置额外的代码,而不仅仅是对 send 方法的调用。 (例如,如果您想同步对不同对象的调用)。

在方法上同步的好处是:

  1. 同步是自动的,由被调用的类决定。调用者不需要知道它。
  2. 您可以根据需要使用同步和非同步方法。

【讨论】:

    猜你喜欢
    • 2011-03-04
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 2020-03-05
    • 1970-01-01
    • 2019-01-17
    • 2011-12-13
    相关资源
    最近更新 更多