forked from ShwoTimeNow/Android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLooperThread.java
More file actions
116 lines (97 loc) · 2.39 KB
/
LooperThread.java
File metadata and controls
116 lines (97 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
* COPYRIGHT NOTICE
* Copyright (C) 2014, ticktick <lujun.hust@gmail.com>
* http://ticktick.blog.51cto.com/
*
* @license under the Apache License, Version 2.0
*
* @file LooperThread.java
* @brief 带Looper的线程封装
*
* @version 1.0
* @author ticktick
* @date 2014/10/15
*
*/
package com.ticktick.juncode.thread;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LooperThread {
private volatile boolean mIsLooperQuit = false;
private Thread mThread;
private Callbak mCallbak;
private Lock mLock = new ReentrantLock();
private Condition mCondition = mLock.newCondition();
private Queue<Message> mMessageQueue = new LinkedList<Message>();
public static class Message {
int what;
}
public static interface Callbak {
public boolean handleMessage(Message msg);
}
public LooperThread( Callbak callback ) {
mCallbak = callback;
}
public void start() {
if( mThread != null ) {
return;
}
mIsLooperQuit = false;
mThread = new Thread(mLooperRunnable);
mThread.start();
}
public void stop() {
if( mThread == null ) {
return;
}
mIsLooperQuit = true;
mLock.lock();
mCondition.signal();
mLock.unlock();
mThread.interrupt();
try {
mThread.join(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
mMessageQueue.clear();
mThread = null;
}
public void sendMessage( Message message ) {
if( mThread == null ) {
return;
}
mLock.lock();
mMessageQueue.add(message);
mCondition.signal();
mLock.unlock();
}
protected Runnable mLooperRunnable = new Runnable() {
@Override
public void run() {
while( !mIsLooperQuit ) {
mLock.lock();
Message message = null;
try {
while( !mIsLooperQuit && mMessageQueue.isEmpty() ) {
mCondition.await();
}
message = mMessageQueue.poll();
}
catch (InterruptedException e) {
e.printStackTrace();
}
finally {
mLock.unlock();
}
if( mCallbak != null && message != null ) {
mCallbak.handleMessage(message);
}
}
}
};
}