Thread

Definition of Synchronized

Synchronized block in java are marked with the synchronized keywork. All synchronized blocks synchronized on the same object can only have one thread executing inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block

The use of thread in Java

Threads allows a program to operate more more efficiently by doing multiple things at the smae time.

Threads can be used to perform complicated tasks in the baackground without interrupting the main program.

线程同步概念

当一个线程对一块内存进行操作的时候,其他的线程都不可以对这块内存进行操作,直到该线程操作完毕,其他线程才可以对其进行操作。

多个线程访问同一个资源会产生线程安全问题,所以要进行加锁

 // 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;
     Sender  sender;
 
     // Receives 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");
        }
    }
 }

Output:

 Sending     Hi 
 Hi Sent
 ​
 Sending     Bye
 Bye Sent

In the above example, we chose to synchronize the Sender object inside the run() method of the ThreadedSend class. Alternately, we could define the whole send() block as synchronized and it would produce the same result. Then we don’t have to synchronize the Message object inside the run() method in ThreadedSend class.

A locak is a thread synchronization mehcanism like synchonized blocks except locaks can be more sophisticated than Java's synchronized blocks. Locks are created using synchronized blocks, so it is no like we can get totally rid of the synchronized keyword

Differences Between Lock and Synchronized Block

There are few differences between the use of synchronized bock and using Lock API's

  • A sysnchronized block is fully contained within a method

  • A synchronized block doesn't support the fairness, any thread can acquire the locak once released, no preference can be specified. We can achieve fairness within the Lock APIs by specifying the fairness property

  • A thread gets blocked if it can't get an access to the synchronized block. The *Lock* API provides *tryLock()* method. The thread acquires lock only if it's available and not held by any other thread.

  • A thread which is in “waiting” state to acquire the access to synchronized block, can't be interrupted. The *Lock* API provides a method *lockInterruptibly()* which can be used to interrupt the thread when it's waiting for the lock

Lock API

  • void locak()

  • void lockInterruptibly()

  • boolean tryLock()

  • boolean tryLock(long timeout, TimeUnit timeUnit)

  • void unlock()

Thread 线程中的 Synchronized block and lock的更多相关文章

  1. [多线程] 线程中的synchronized关键字锁

    为什么要用锁? 在多线程中,难免会出现在多个线程中对同一个对象的实例变量或者全局静态变量进行并发访问的情况,如果不做正确的同步处理,那么产生的后果就是"脏读",也就是取到的数据其实 ...

  2. Android开发之ProgressDialog在独立Thread线程中更新进度

    简单的需求:在一个工作Thread中更新进度对话框ProgressDialog 遇到的问题: 1,创建需要Context,这个需要传进来 2,Thread中不能创建ProgressDialog,否则需 ...

  3. 在线程中调用SaveFileDialog

    在多线程编程中,有时候可能需要在单独线程中执行某些操作.例如,调用SaveFileDialog类保存文件.首先,我们在Main方法中创建了一个新线程,并将其指向要执行的委托SaveFileAsyn.在 ...

  4. Java基础学习笔记: 多线程,线程池,同步锁(Lock,synchronized )(Thread类,ExecutorService ,Future类)(卖火车票案例)

    多线程介绍 学习多线程之前,我们先要了解几个关于多线程有关的概念.进程:进程指正在运行的程序.确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于运行过程中的程序,并且具有一定独立功能. 线 ...

  5. Java核心知识点学习----线程中如何创建锁和使用锁 Lock,设计一个缓存系统

    理论知识很枯燥,但这些都是基本功,学完可能会忘,但等用的时候,会发觉之前的学习是非常有意义的,学习线程就是这样子的. 1.如何创建锁? Lock lock = new ReentrantLock(); ...

  6. Java核心知识点 --- 线程中如何创建锁和使用锁 Lock , 设计一个缓存系统

    理论知识很枯燥,但这些都是基本功,学完可能会忘,但等用的时候,会发觉之前的学习是非常有意义的,学习线程就是这样子的. 1.如何创建锁? Lock lock = new ReentrantLock(); ...

  7. -1-5 java 多线程 概念 进程 线程区别联系 java创建线程方式 线程组 线程池概念 线程安全 同步 同步代码块 Lock锁 sleep()和wait()方法的区别 为什么wait(),notify(),notifyAll()等方法都定义在Object类中

     本文关键词: java 多线程 概念 进程 线程区别联系 java创建线程方式 线程组 线程池概念 线程安全 同步 同步代码块 Lock锁  sleep()和wait()方法的区别 为什么wait( ...

  8. 线程中消费者生产者的实例代码(使用Lock类)

    http://www.cnblogs.com/DreamDrive/p/6192685.html 这个是用synchronized关键字实现的. Lock可以替换synchronized. 上面用来做 ...

  9. Python进阶(3)_进程与线程中的lock(线程中互斥锁、递归锁、信号量、Event对象、队列queue)

    1.同步锁 (Lock) 当全局资源(counter)被抢占的情况,问题产生的原因就是没有控制多个线程对同一资源的访问,对数据造成破坏,使得线程运行的结果不可预期.这种现象称为“线程不安全”.在开发过 ...

  10. 线程中的join方法,与synchronized和wait()和notify()的关系

    什么时候要用join()方法? 1,join方法是Thread类中的方法,主线程执行完start()方法,线程就进入就绪状态,虚拟机最终会执行run方法进入运行状态.此时.主线程跳出start方法往下 ...

随机推荐

  1. HTTP协议中的长连接和短链接

    一.概念 HTTP长连接,也称持久连接,是使用同一个TCP连接来发送和接受多个HTTP请求/应答,而不是位每一个新的请求/应答打开新的TCP连接.这种方式由于通信连接一直存在,此种方式常用于P2P通信 ...

  2. 将npm安装镜像切换到淘宝

    cnpm(推荐) 安装 pm install cnpm -g --registry=https://registry.npm.taobao.org 使用 cnpm install [xxxxxxx] ...

  3. 【python】第二模块 步骤一 第二课、数据库表的相关操作

    第二课.数据库表的相关操作 一.课程介绍 1.1 课程介绍 学习目标 管理逻辑库和数据表 创建.删除.修改逻辑库和数据表 了解常用的数据类型和约束 字符串.整数.浮点数.精确数字.日期.枚举.主要约束 ...

  4. systick 理解

    systick 中断的优先级往往设置为最低值,而不是最高值:如果设置为最低值不会发生上图标号[6]处的情况,设置为最低可能会被其他中断抢占,延长systick的响应时间,但是这个延迟不会累计,因为sy ...

  5. SelectionSort,选择排序,C++实现

    1 // g++ selection_sort.cc -Wall -O3 -std=c++11 && ./a.exe 2 3 4 #include <iostream> 5 ...

  6. rgb变为灰度图像

    close all;clc; x = imread('C:\timg.jpg'); %读取rgb图片信息I = rgb2gray(x);%将rgb图像转化为灰度图像 set(0,'defaultFig ...

  7. 水印 canvas 实现

    let str = info; let c = document.createElement("canvas"); document.body.appendChild.c; let ...

  8. 正确理解RestFul 接口

    一.REST# REST,即Representational State Transfer的缩写,翻译过来就是"表现层状态转化".不得不承认,我在刚开始看到这个名词的时候是一脸懵逼 ...

  9. css3样式pointer-events,点击穿透和海市蜃楼的效果

    css样式pointer-events pointer-events 是CSS3的一个属性,支持的值非常多,其中大部分都是和SVG有关.目前只了解 none 这个值, 其他值后续要补上. pointe ...

  10. Linux下将普通用户文件移动到root用户下

    步骤: 将普通用户的文件拷贝到tmp目录下 cp /Desktop/1.txt /tmp 从普通用户切到root用户 su - root用户从tmp中取文件到指定目录/var/test cp /tmp ...