Synchronized在java中是一个关键字,在kotlin中是一个注解类
/**
- Marks the JVM method generated from the annotated function as
synchronized
, meaning that the method - will be protected from concurrent execution by multiple threads by the monitor of the instance (or,
- for static methods, the class) on which the method is defined.
*/
@Target(FUNCTION, PROPERTY_GETTER, PROPERTY_SETTER)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
public actual annotation class Synchronized
我们复习一下java中的Synchronized关键字:
Synchronized关键字可以保证加锁对象在多线程环境下同时只有一个线程能够执行,在当前线程释放对象锁之后其他线程才能获取。synchronized同时能够保证共享变量的可见性。
基本规则:
- 对于普通方法,锁的是当前对象
- 对于静态方法,锁的是class类
- 对于代码块加锁,锁的是代码块内对象
一个线程访问对象的synchronized区域时,其他线程访问该对象synchronized区域将会阻塞,但是其他线程可以访问该对象的非同步区域。
1.1 java中的synchronized使用
略略略
1.2 kotlin中的synchronized使用
对方法加锁
对方法加锁的时候只需要加上@Synchronized 注解就Ok了,比如我们定义了以下方法:
@Synchronized
private fun postResult(s: String){
println(“
S
y
s
t
e
m
.
c
u
r
r
e
n
t
T
i
m
e
M
i
l
l
i
s
(
)
:
{System.currentTimeMillis()} :
System.currentTimeMillis():s” )
sleep(5000)
}
在不同的线程中调用该方法:
fun testFunSync() {
Thread{
postResult(“first thread”)
}.start()
Thread{
postResult(“second thread”)
}.start()
}
第一个线程调用postResult方法,输出当前时间后阻塞5s。5s之后第二个线程才能获取postResult 的锁。
输出结果:
1622794297695 ��first thread
1622794302698 ��second thread
输出结果和我们预想的一样,相差5s
如果我们将第一个线程进行阻塞呢,此时锁的获取情况是什么样的?
fun testFunSync() {
Thread{
postResult(“first thread”)
//我们在此线程阻塞10s,看下结果是否一样
sleep(10000)
}.start()
Thread{
postResult(“second thread”)
}.start()
}
1622794450105 ��first thread
1622794455107 ��second thread
输出结果依旧是一样的,first线程在执行玩postResult之后就会释放锁,后续的操作不会影响second线程获取postResult的锁
对类加锁
首先我们创建一个Result类:
class Result {
var s : String = “”
public fun printResult(){
println(“
S
y
s
t
e
m
.
c
u
r
r
e
n
t
T
i
m
e
M
i
l
l
i
s
(
)
:
{System.currentTimeMillis()} :
System.currentTimeMillis():s” )
Thread.sleep(5000)
}
}
调用
fun testClassSync() {
val result= Result()
Thread{
synchronized(result){
result.s = currentThread().name
result.printResult()
}
}.apply {
name = “first thread”
start()
}
Thread{
synchronized(result){
result.s = currentThread().name
result.printResult()
}
}.apply {
name = “second thread”
start()
}
}
输出结果:
1622795509253 ��first thread
1622795514269 ��second thread
//时间相差5s,说明锁生效了
以上就是对Result类对象加锁,如果Result类有多个实例对象怎么办?我们稍微修改下调用方法:
fun testClassSync() {
val result= Result()
//Result类的多个实例对象
val result2= Result()
Thread{
synchronized(result){
result.s = currentThread().name
result.printResult()
}
}.apply {
name = “first thread”
start()
}
Thread{
synchronized(result2){
result2.s = currentThread().name
result2.printResult()
}
}.apply {
name = “second thread”
start()
}
}
创建了多个Result类对象,first线程对A对象加锁,并不会影响second线程获取B对象锁,输出结果:
1622795623480 ��first thread
1622795623480 ��second thread
如果我们对Result类加锁,那所有的对象将会共享同一锁:
fun testClassSync() {
val result= Result()
val result2= Result()
//对Result类加锁
Thread{
synchronized(Result::class.java){
result.s = currentThread().name
result.printResult()
}
}.apply {
name = “first thread”
start()
}
Thread{
synchronized(Result::class.java){
result2.s = currentThread().name
result2.printResult()
}
}.apply {
name = “second thread”
start()
}
}
输出结果:
1622796124320 ��first thread
1622796129336 ��second thread
尽管first线程和second线程调用的是不同对象,但是first线程对Resutl类加上了类锁,second线程只能乖乖等着。
输出结果表示:对xx::class.java加上类锁的时候,该类所有的对象将会共享同一锁。
2.Lock
lock是一个接口,我们常用的实现类有ReentrantLock,意思是可重入锁。
我们定义一个全局变量,在两个线程中同时进行写操作,同时start两个线程
fun testLockSync() {
var count = 0
val thread1 = Thread{
for (i in 0…1000){
count += i
}
println(“
T
h
r
e
a
d
.
c
u
r
r
e
n
t
T
h
r
e
a
d
(
)
.
n
a
m
e
:
c
o
u
n
t
:
{Thread.currentThread().name} : count:
Thread.currentThread().name:count:{count}”)
}
val thread2 = Thread{
for (i in 0…1000){
count += i
}
println(“
T
h
r
e
a
d
.
c
u
r
r
e
n
t
T
h
r
e
a
d
(
)
.
n
a
m
e
:
c
o
u
n
t
:
{Thread.currentThread().name} : count:
Thread.currentThread().name:count:{count}”)
}
//同时开启两个线程
thread1.start()
thread2.start()
}
输出结果:会发现每次输出的结果都不一样
Thread-1 : count:505253
Thread-2 : count:1001000
Thread-2 : count:1001000
Thread-1 : count:1001000
Thread-2 : count:822155
Thread-1 : count:822155
使用ReentrantLock保证线程安全:
fun testLockSync() {
val lock = ReentrantLock()
var count = 0
val thread1 = Thread{
lock.lock()
for (i in 0…1000){
count += i
}
println(“
T
h
r
e
a
d
.
c
u
r
r
e
n
t
T
h
r
e
a
d
(
)
.
n
a
m
e
:
c
o
u
n
t
:
{Thread.currentThread().name} : count:
Thread.currentThread().name:count:{count}”)
lock.unlock()
}
val thread2 = Thread{
lock.lock()
for (i in 0…1000){
count += i
}
println(“
T
h
r
e
a
d
.
c
u
r
r
e
n
t
T
h
r
e
a
d
(
)
.
n
a
m
e
:
c
o
u
n
t
:
{Thread.currentThread().name} : count:
Thread.currentThread().name:count:{count}”)
lock.unlock()
}
thread1.start()
thread2.start()
}
输出结果和执行顺序每次都是一样:
Thread-1 : count:500500
Thread-2 : count:1001000
Lock常用方法
- lock() :获取锁,获取成功设置当前线程count++,如果其他线程占有锁,则当前线程不可用,等待。
- tryLock() : 获取锁,如果锁不可用,则此方法将立即返回,线程不阻塞,可设置等待时间。
- unLock() : 尝试释放锁,当前thread count–,如果count为0,则释放锁。
2.Object
在kotlin中object有很多作用,可以实现对象表达式、对象声明等
对象表达式就是创建一个Object类,实现单例模式:
object Singleton {
}
在idea中查看其反编译java代码:
public final class Singleton {
public static final Singleton INSTANCE;
private Singleton() {
}
static {
Singleton var0 = new Singleton();
INSTANCE = var0;
}
}
可以看到其属于饿汉模式: 优点是在类加载的时候创建,不会存在线程安全问题,效率高。缺点就是浪费资源。具体可以参考此链接
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以添加V获取:vip204888 (备注Android)
最后
在这里小编整理了一份Android大厂常见面试题,和一些Android架构视频解析,都已整理成文档,全部都已打包好了,希望能够对大家有所帮助,在面试中能顺利通过。
喜欢本文的话,不妨顺手给我点个小赞、评论区留言或者转发支持一下呗
一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
w-1712757352480)]
最后
在这里小编整理了一份Android大厂常见面试题,和一些Android架构视频解析,都已整理成文档,全部都已打包好了,希望能够对大家有所帮助,在面试中能顺利通过。
[外链图片转存中…(img-RCndtBUx-1712757352481)]
[外链图片转存中…(img-nUkOooWz-1712757352481)]
喜欢本文的话,不妨顺手给我点个小赞、评论区留言或者转发支持一下呗
一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
[外链图片转存中…(img-2NdGDTMA-1712757352482)]