方法一:轮训
比如主线程要等子线程在得到变量“val”值的时候开始用“val”的值来进行工作,使用轮训的方法如下:
public class SubThread extends Thread{ private boolean flag = false;//标志位,用来标识是否应该通知主线程或者其他对象改做事情了 @Override public void run() { super.run(); for(int i=0;i<5;i++){ System.out.println(Thread.currentThread().getName() + " do " + i + "thing"); } flag = true; for(int i=5;i<10;i++){ System.out.println(Thread.currentThread().getName() + " do " + i + "thing"); } } public boolean getFlag(){ return flag; } }public class Test { public static void main(String[] args) { SubThread subThread = new SubThread(); subThread.start(); while(true){ if(subThread.getFlag()){ System.out.println(Thread.currentThread().getName() + " do something ..."); doWork(); break; } } } private static void doWork() { System.out.println(Thread.currentThread().getName() + " do work ..."); } }
可以看出确实实现了效果,但是这种方法太low了,缺点如下:
(1)主线程循环判断标志位是浪费CPU的表现
(2)如果有另外的线程也需要判断,那也得在线程中写一个死循环,代码太无设计思想可言
,看到这里也许有有人已经想到另外一种方法——回调!
方法二,回调
回调就是调用别的对象的方法时把“自己”传进去,然后别的对象在某个时候调用“自己的方法”,代码如下
public interface ThreadCallback { void threadStartLisener(); void threadEndLisener(); }public class SubRunnable implements Runnable { private ThreadCallback mThreadCallback; public SubRunnable(ThreadCallback threadCallback){ this.mThreadCallback = threadCallback; } @Override public void run() { mThreadCallback.threadStartLisener(); for(int i=0;i<5;i++){ System.out.println(Thread.currentThread().getName() + " do something "+i); } mThreadCallback.threadEndLisener(); } }public class ThreadCallbackTest implements ThreadCallback{ private static ThreadCallbackTest mThreadCallbackTest = new ThreadCallbackTest(); public static void main(String[] args) { System.out.println(Thread.currentThread().getName() + " 开始"); new Thread(new SubRunnable(mThreadCallbackTest)).start(); } @Override public void threadStartLisener() { System.out.println(Thread.currentThread().getName() + " 线程,知道SubRunnable线程开始执行任务了"); } @Override public void threadEndLisener() { System.out.println(Thread.currentThread().getName() + " 线程,知道SubRunnable线程任务执行结束了"); } }
输出结果如下:
main 开始
Thread-0 线程,知道SubRunnable线程开始执行任务了
Thread-0 do something 0
Thread-0 do something 1
Thread-0 do something 2
Thread-0 do something 3
Thread-0 do something 4
Thread-0 线程,知道SubRunnable线程任务执行结束了
发现threadStartLisener()方法和threadEndLisener()方法都是在子线程中执行的。就是说虽然两个回调方法都成功执行了,但是执行所用的线程确是不正确的。