线程间通信"/>
Java / Android 线程间通信
thread.stop 这个方法会强制中断线程操作 已被弃用
thread.interrupt 会在合适的时机终止线程,也就是做一个标记为中断,非强制中断
if (isInterrupted()){return;}
获取线程状态,然后根据状态判断
Thread.interrupted() 会把当前线程状态改为中断,并改变其值为true
try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}
thread.sleep --- InterruptedException //等待状态的线程的终止
如果线程在sleep时,调用了thread.interrupt() 则会抛出这个异常
可以使用SystemClock.sleep 不会抛异常
wait() ---> notify notifyAll
wait 当线程操作数据较慢则使用wait等待时机,然后通过notify 或者notifyAll 进行通知, 然后再进行操作
public class WaitDemo implements TestDemo{private String sharedString;private synchronized void initString(){sharedString = "hello luxiaofeng";notifyAll();}private synchronized void printString(){while (sharedString == null){//synchronized 会一直持有锁try {wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}System.out.println(sharedString);}@Overridepublic void runTest() {final Thread thread1 = new Thread(){@Overridepublic void run() {try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}printString();}};thread1.start();Thread thread2 = new Thread(){@Overridepublic void run() {try {Thread.sleep(2000);} catch (InterruptedException e) {throw new RuntimeException(e);}initString();}};thread2.start();}
}
wait是Object的方法,
private Object monitor = new Object();
private void printString(){synchronized (monitor){while (sharedString == null){//synchronized 会一直持有锁try {wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}}System.out.println(sharedString);}
如果使用的是对象锁,调用wait()方法会报错:
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
这个时候需要使用对象的wait ------
monitor.wait(); 然后也需要调用对象的notify 和 这个对象的锁
private void initString() {synchronized (monitor){sharedString = "hello luxiaofeng";
// notifyAll();monitor.notifyAll();}}private void printString() {synchronized (monitor) {while (sharedString == null) {//synchronized 会一直持有锁try {monitor.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}}System.out.println(sharedString);}
public class WaitDemo implements TestDemo {private String sharedString;private Object monitor = new Object();private void initString() {synchronized (monitor){sharedString = "hello luxiaofeng";
// notifyAll();this.monitor.notifyAll();}}private void printString() {synchronized (monitor) {while (sharedString == null) {//synchronized 会一直持有锁try {monitor.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}}System.out.println(sharedString);}@Overridepublic void runTest() {final Thread thread1 = new Thread() {@Overridepublic void run() {try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}printString();}};thread1.start();Thread thread2 = new Thread() {@Overridepublic void run() {try {Thread.sleep(2000);} catch (InterruptedException e) {throw new RuntimeException(e);}initString();}};thread2.start();System.out.println("666");}
}
更多推荐
Java / Android 线程间通信
发布评论