使用Unsafe來實現自定義鎖

2022-01-18 16:51:16 字數 1645 閱讀 3411

1.使用unsafe類

import

sun.misc.unsafe;

class

unsafepackage

catch

(exception ex)

}public

static

unsafe getunsafe()

}

2.宣告簡單鎖

class

customlock

catch

(exception ex)

}private

boolean comareandsetstatus(int originalstatus, int

updatestatus)

public

boolean

lock()

"競爭鎖失敗!進入等待佇列");

push(thread.currentthread());

while (!comareandsetstatus(0, 1))

return

true

; }

public

boolean

unlock()

return

true

; }

private

void

push(thread thread)

private

thread pop()

}

3.競爭鎖失敗的進佇列

class

waitingqueue

catch

(exception ex)

}public

void

push(thread thread)

queue.offerlast(thread);

comareandsetstatus(1, 0);

return

; }

public

thread pop()

thread elem = null

;

if (!queue.isempty())

comareandsetstatus(1, 0);

return

elem;

}private

boolean comareandsetstatus(int originalstatus, int

updatestatus)

}

3.呼叫如下

public

class

customlocktest

countdownlatch.countdown();

} finally

}}.start();

});countdownlatch.await();

long end =system.currenttimemillis();

system.out.println("結果值為:" + count + ",共花費了" + (end - start) + "毫秒!");

}}

結果值為:1500000,共花費了601毫秒!

通過自定義ImageView來實現多點觸控

public class main extends activity 觸屏事件 override public boolean ontouchevent motionevent event else if event.getpointercount 1 return true 自定義imagevie...

GIL鎖和自定義互斥鎖

from threading import thread,lock,current thread import time n 100 mutex lock def task global n mutex.acquire time.sleep 1 print current thread getnam...

自定義Toast實現自定義Toast布局

平時我們使用toast的時候都是這樣的一種方法 toast toast toast.maketext context,duration 現在我們來自定義下toast的布局,首先看下toast建立時的源 public static toast maketext context context,char...