Android-线程同步
1 package com.csizg.jniport; 2 3 4 import java.util.ArrayList; 5 import java.util.List; 6 7 /** 8 * 与芯片交互线程 9 */ 10 public class SpiQueue implements Runnable { 11 12 private static final String TAG = SpiQueue.class.getSimpleName(); 13 14 private static final byte INIT = 0;// 初始化 15 private static final byte RUNNING = 1;// 执行中 16 private static final byte WITING = 2;// 暂停等待中 17 private static final byte DONE = 3;// 结束 18 19 private byte state = INIT;// 执行状态 20 21 private static SpiQueue spiQueue = null; 22 23 private SpiQueue() { 24 25 } 26 27 public static SpiQueue getSpiQueue() { 28 if (spiQueue == null) { 29 spiQueue = new SpiQueue(); 30 } 31 return spiQueue; 32 } 33 34 private Thread thread; 35 private List<SpiTask> tasks = new ArrayList<>(); 36 37 @Override 38 public void run() { 39 state = RUNNING; 40 while (state != DONE) { 41 synchronized (this) { 42 SpiTask currentTask = getNextTask(); 43 if (currentTask == null) { 44 System.out.println(TAG + " run " + "no task todo begin to waiting"); 45 try { 46 state = WITING; 47 wait(); 48 } catch (InterruptedException e) { 49 e.printStackTrace(); 50 } 51 } else { 52 try { 53 Thread.sleep(10); 54 } catch (InterruptedException e) { 55 e.printStackTrace(); 56 } 57 System.out.println(TAG + " run " + "currentTask = " + currentTask.toString()); 58 } 59 } 60 } 61 62 } 63 64 private synchronized SpiTask getNextTask() { 65 System.out.println(TAG + " getNextTask " + "tasks.size() = " + tasks.size()); 66 if (tasks.size() > 0) { 67 SpiTask task = tasks.remove(0); 68 return task; 69 } 70 return null; 71 } 72 73 public synchronized void addTask(SpiTask task) { 74 System.out.println(TAG + " addTask " + "tasks.size() = " + tasks.size() + ", new task : " + task.getCode()); 75 if (state == DONE) { 76 System.out.println(TAG + " addTask " + "Thread is DONE : task : " + task.getCode()); 77 return; 78 } 79 tasks.add(task); 80 if (state != RUNNING) { 81 synchronized (this) { 82 state = RUNNING; 83 System.out.println(TAG + " addTask notifyAll "); 84 notifyAll(); 85 } 86 } 87 } 88 89 public synchronized void start() { 90 System.out.println(TAG + " start " + "state = " + state); 91 if (state == RUNNING || state == WITING) { 92 return; 93 } 94 state = INIT; 95 // 运行本线程 96 tasks.clear(); 97 if (thread != null) { 98 thread.interrupt(); 99 } 100 thread = new Thread(this); 101 thread.start(); 102 } 103 104 105 public synchronized void stop() { 106 state = DONE; 107 tasks.clear(); 108 synchronized (this) { 109 notifyAll(); 110 } 111 } 112 }