标签:
线程间通讯
java
方法一 通过访问共享变量的方式(注:需要处理同步问题)
通过内部类实现线程的共享变量
通过实现Runnable接口实现线程的共享变量
方法二 通过管道流
方法一 通过内部类实现线程的共享变量
public class Innersharethread { public static void main(String[] args) { Mythread mythread = new Mythread(); mythread.getThread().start(); mythread.getThread().start(); mythread.getThread().start(); mythread.getThread().start(); } }
class Mythread { int index = 0; private class InnerThread extends Thread { public synchronized void run() { while (true) { System.out.println(Thread.currentThread().getName() + "is running and index is " + index++); } } } public Thread getThread() { return new InnerThread(); } }
方法二(通过管道流)
public class CommunicateWhitPiping { public static void main(String[] args) { /** * 创建管道输出流 */ PipedOutputStream pos = new PipedOutputStream(); /** * 创建管道输入流 */ PipedInputStream pis = new PipedInputStream(); try { /** * 将管道输入流与输出流连接 此过程也可通过重载的构造函数来实现 */ pos.connect(pis); } catch (IOException e) { e.printStackTrace(); } /** * 创建生产者线程 */ Producer p = new Producer(pos); /** * 创建消费者线程 */ Consumer c = new Consumer(pis); /** * 启动线程 */ p.start(); c.start(); } } /** * 生产者线程(与一个管道输入流相关联) * */ class Producer extends Thread { private PipedOutputStream pos; public Producer(PipedOutputStream pos) { this.pos = pos; } public void run() { int i = 8; try { pos.write(i); } catch (IOException e) { e.printStackTrace(); } } } /** * 消费者线程(与一个管道输入流相关联) * */ class Consumer extends Thread { private PipedInputStream pis; public Consumer(PipedInputStream pis) { this.pis = pis; } public void run() { try { System.out.println(pis.read()); } catch (IOException e) { e.printStackTrace(); } } }
android
android提供了以下几种方法,用于实现后台线程与UI线程的交互。
更新UI的5种方式 1.handler机制 2.Asynctask-实际 FutureTask Handler 封装 3.Activity中的runOnUIThread - mHandler.post(action); - Handler.sendMessageDelayed(getPostMessage(r), 0); 4.view.post(Runnable); 5.view.postDelayed(Runnable,long);
handler机制
View -
public boolean post(Runnable action) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler.post(action); } // Assume that post will succeed later ViewRootImpl.getRunQueue().post(action); return true; }
public boolean postDelayed(Runnable action, long delayMillis) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler.postDelayed(action, delayMillis); } // Assume that post will succeed later ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); return true; }
标签:
原文地址:http://my.oschina.net/kylinhuang/blog/472142