java同步_Java同步

java同步

Synchronization is a process of handling resource accessibility by multiple thread requests. The main purpose of synchronization is to avoid thread interference. At times when more than one thread try to access a shared resource, we need to ensure that resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. The synchronization keyword in java creates a block of code referred to as critical section.

同步是处理多个线程请求的资源可访问性的过程。 同步的主要目的是避免线程干扰。 当多个线程尝试访问共享资源时,我们需要确保一次只能由一个线程使用资源。 实现此目标的过程称为同步。 Java中的sync关键字创建称为关键部分的代码块。

General Syntax:

通用语法:

synchronized (object)
{
  //statement to be synchronized
}

Every Java object with a critical section of code gets a lock associated with the object. To enter critical section a thread need to obtain the corresponding object's lock.

每个具有关键代码段的Java对象都会获得一个与该对象关联的锁。 要进入关键部分,线程需要获取相应对象的锁。

为什么我们需要同步化? (Why we need Syncronization?)

If we do not use syncronization, and let two or more threads access a shared resource at the same time, it will lead to distorted results.

如果我们不使用同步化,而让两个或多个线程同时访问共享资源,则会导致结果失真。

Consider an example, Suppose we have two different threads T1 and T2, T1 starts execution and save certain values in a file temporary.txt which will be used to calculate some result when T1 returns. Meanwhile, T2 starts and before T1 returns, T2 change the values saved by T1 in the file temporary.txt (temporary.txt is the shared resource). Now obviously T1 will return wrong result.

考虑一个例子,假设我们有两个不同的线程T1T2 ,T1开始执行并将某些值保存在文件临时文件.txt中 ,该文件将在T1返回时用于计算某些结果。 同时,T2开始,在T1返回之前,T2更改T1保存在文件secondary.txt(temporary.txt是共享资源)中的值。 现在显然T1将返回错误的结果。

To prevent such problems, synchronization was introduced. With synchronization in above case, once T1 starts using temporary.txt file, this file will be locked(LOCK mode), and no other thread will be able to access or modify it until T1 returns.

为了防止此类问题,引入了同步。 在上述情况下,如果使用同步,则一旦T1开始使用temporary.txt文件,该文件将被锁定 (LOCK模式),直到T1返回之前,其他线程都无法访问或修改它。

使用同步方法 (Using Synchronized Methods)

Using Synchronized methods is a way to accomplish synchronization. But lets first see what happens when we do not use synchronization in our program.

使用同步方法是完成同步的一种方法。 但是首先让我们看看当我们不在程序中使用同步时会发生什么。

没有同步的示例 (Example with no Synchronization)

In this example, we are not using synchronization and creating multiple threads that are accessing display method and produce the random output.

在此示例中,我们没有使用同步,而是创建了多个正在访问显示方法并产生随机输出的线程。

class First
{
  public void display(String msg)
  {
    System.out.print ("["+msg);
    try
    {
      Thread.sleep(1000);
    }
    catch(InterruptedException e)
    {
      e.printStackTrace();
    }
    System.out.println ("]");
  }
}

class Second extends Thread
{
  String msg;
  First fobj;
  Second (First fp,String str)
  {
    fobj = fp;
    msg = str;
    start();
  }
  public void run()
  {
    fobj.display(msg);
  }
}

public class Syncro
{
  public static void main (String[] args)
  {
    First fnew = new First();
    Second ss = new Second(fnew, "welcome");
    Second ss1= new Second(fnew,"new");
    Second ss2 = new Second(fnew, "programmer");
  }
}

[welcome [ new [ programmer] ] ]

[欢迎[新[程序员]]

In the above program, object fnew of class First is shared by all the three running threads(ss, ss1 and ss2) to call the shared method(void display). Hence the result is nonsynchronized and such situation is called Race condition..

在上面的程序中,类First的对象fnew由所有三个运行线程(ss,ss1和ss2)共享,以调用共享方法(无效显示 )。 因此,结果是不同步的,这种情况称为“ 竞赛条件”

同步关键字 (Synchronized Keyword)

To synchronize above program, we must synchronize access to the shared display() method, making it available to only one thread at a time. This is done by using keyword synchronized with display() method.

要同步上述程序,我们必须同步对共享display()方法的访问,使其一次只能用于一个线程。 这可以通过使用与display()方法同步的关键字来完成。

synchronized void display (String msg)

示例:同步方法的实现 (Example : implementation of synchronized method)

class First
{
  synchronized public void display(String msg)
  {
    System.out.print ("["+msg);
    try
    {
      Thread.sleep(1000);
    }
    catch(InterruptedException e)
    {
      e.printStackTrace();
    }
    System.out.println ("]");
  }
}

class Second extends Thread
{
  String msg;
  First fobj;
  Second (First fp,String str)
  {
    fobj = fp;
    msg = str;
    start();
  }
  public void run()
  {
    fobj.display(msg);
  }
}

public class MyThread
{
  public static void main (String[] args)
  {
    First fnew = new First();
    Second ss = new Second(fnew, "welcome");
    Second ss1= new Second(fnew,"new");
    Second ss2 = new Second(fnew, "programmer");
  }
}

[welcome] [programmer] [new]

[欢迎] [程序员] [新]

使用同步块 (Using Synchronized block)

If want to synchronize access to an object of a class or only a part of a method to be synchronized then we can use synchronized block for it. It is capable to make any part of the object and method synchronized.

如果要同步访问类的对象或仅要同步的方法的一部分,则可以对其使用同步块。 它能够使对象和方法的任何部分同步。

(Example)

In this example, we are using synchronized block that will make the display method available for single thread at a time.

在此示例中,我们使用同步块,该显示块将使显示方法一次可用于单个线程。

class First
{
  public void display(String msg)
  {
    System.out.print ("["+msg);
    try
    {
      Thread.sleep(1000);
    }
    catch(InterruptedException e)
    {
      e.printStackTrace();
    }
    System.out.println ("]");
  }
}

class Second extends Thread
{
  String msg;
  First fobj;
  Second (First fp,String str)
  {
    fobj = fp;
    msg = str;
    start();
  }
  public void run()
  {
    synchronized(fobj)      //Synchronized block
    {
      fobj.display(msg);
    }
  }
}

public class MyThread
{
  public static void main (String[] args)
  {
    First fnew = new First();
    Second ss = new Second(fnew, "welcome");
    Second ss1= new Second (fnew,"new");
    Second ss2 = new Second(fnew, "programmer");
  }
}

[welcome] [new] [programmer]

[欢迎] [新] [程序员]

Because of synchronized block this program gives the expected output.

由于同步块,该程序可提供预期的输出。

同步关键字和同步块之间的区别 (Difference between synchronized keyword and synchronized block)

When we use synchronized keyword with a method, it acquires a lock in the object for the whole method. It means that no other thread can use any synchronized method until the current thread, which has invoked it's synchronized method, has finished its execution.

当我们将同步关键字与方法一起使用时,它将为整个方法获取对象的锁定。 这意味着在调用了其同步方法的当前线程完成其执行之前,没有其他线程可以使用任何同步方法。

synchronized block acquires a lock in the object only between parentheses after the synchronized keyword. This means that no other thread can acquire a lock on the locked object until the synchronized block exits. But other threads can access the rest of the code of the method.

同步块仅在synced关键字之后的括号之间获取对象的锁定。 这意味着在同步块退出之前,没有其他线程可以获取对锁定对象的锁定。 但是其他线程可以访问该方法的其余代码。

哪个更优选-同步方法还是同步块? (Which is more preferred - Synchronized method or Synchronized block?)

In Java, synchronized keyword causes a performance cost. A synchronized method in Java is very slow and can degrade performance. So we must use synchronization keyword in java when it is necessary else, we should use Java synchronized block that is used for synchronizing critical section only.

在Java中,synced关键字会导致性能损失。 Java中的同步方法非常慢,并且可能降低性能。 因此,在其他必要时,我们必须在java中使用syncin关键字,而应该使用Java同步块,该块仅用于同步关键部分。

翻译自: https://www.studytonight.com/java/synchronization.php

java同步

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值