考察线程同步,wait, notify用法
sychronized 解决线程同步问题 ;wait, notify作用是线程间通信
三个线程,定义Runnable,参数是3的余数
class ThreadTask(threadNo: Int, threadCnt: Int) :Runnable{
var threadCount = threadCnt
var threadNu = threadNo
companion object{
val max = 15 //静态变量,循环的最大值
val LOCK:Object = Object()
var current = 1
}
override fun run() {
while(true) { //保证单个线程连续执行
synchronized (LOCK) { //线程同步 , ⚠️ wait和notify必须用在锁对象上
// 判断是否轮到当前线程执行 ,没轮到则释放锁 等待其他线程nofity
while (current % threadCount != threadNu) {
if (current > max) {
break
}
try {
// 如果不是,则当前线程进入wait
LOCK.wait()
} catch (e:InterruptedException) {
e.printStackTrace()
}
}
// 最大值跳出循环
if (current > max) {
return
}
Log.d("TAG","Thread"+threadNu+":"+ current)
current++;
// 唤醒其他wait线程
LOCK.notifyAll()
}
}
}
}
//调用
Thread(ThreadTask(0,3)).start()
Thread(ThreadTask(1,3)).start()
Thread(ThreadTask(2,3)).start()
打印结果:
Thread1:1
Thread2:2
Thread0:3
Thread1:4
Thread2:5
Thread0:6
Thread1:7
Thread2:8
Thread0:9
Thread1:10
Thread2:11
Thread0:12
Thread1:13
Thread2:14
Thread0:15
3个线程依次打印ABC,各打10次。
上面打印内容和count最大值稍作修改即可
class ThreadTask(threadNo: Int, threadCnt: Int) :Runnable{
var threadCount = threadCnt
var threadNu = threadNo
companion object{
val max = 30
val LOCK:Object = Object()
var current = 1
}
override fun run() {
while(true) {
synchronized (LOCK) {
// 判断是否轮到当前线程执行
while (current % threadCount != threadNu) {
if (current > max) {
break
}
try {
// 如果不是,则当前线程进入wait
LOCK.wait()
} catch (e:InterruptedException) {
e.printStackTrace()
}
}
// 最大值跳出循环
if (current > max) {
return
}
if(threadNu == 1){
print("A")
}
if(threadNu == 2){
print("B")
}
if(threadNu == 0){
print("C")
}
current++;
// 唤醒其他wait线程
LOCK.notifyAll()
}
}
}
ABCABCABCABCABCABCABCABCABCABC
LOCK:
网友评论