多线程基础与回调

工作了一年了,一直没怎么多用线程一块,好薄弱,,今天看了看。自己写了个小例子。免的以后忘了。做的主要是线程监控返回值。即不用轮训,和设置变量。让线程通知主类(我做完活东西给你了。)

        直接上代码吧。
 package com.bjz;

/**
 * 实现
 * @author bjz
 *
 */
public interface CallbackListener {
	public void srtartCallbackThread();

	public void print(String returnResult);  //主要实现方法,为什么不红了???

}


接口只要是供调用线程的类实现。从而实现线程和调用方法的解耦(ps:线程对主类)
package com.bjz;

public class Reciver implements CallbackListener {
	private String num;
	private int count;

	String result;

	public Reciver(String num, int count) {
		this.num = num;
		this.count = count;
	}

	@Override
	public void srtartCallbackThread() {
		CallbackAndThread callbackAndThread = new CallbackAndThread(num, count);
		callbackAndThread.addList(this);
		new Thread(callbackAndThread).start();
		
	}

	[color=darkred]@Override
	public void print(String returnResult) {
		this.result = returnResult;
		System.out.println(result);
	}[/color]   //主要实现方法,为什么不红了???
}


下来就是线程了
package com.bjz;

import java.util.List;
import java.util.ListIterator;
import java.util.Vector;

public class CallbackAndThread implements Runnable {

	private String note;
	private int count;
	private List listenerList = new Vector();

	public CallbackAndThread(String note, int count) {
		this.note = note;
		this.count = count;
	}

	public void addList(CallbackListener listener) {
		listenerList.add(listener);
	}

	public void removeList(CallbackListener listener) {
		listenerList.remove(listener);
	}
[color=darkred]
	public synchronized void returnResult(String note, int count) {
		ListIterator iterator = listenerList.listIterator();
		while (iterator.hasNext()) {
			CallbackListener listener = (CallbackListener) iterator.next();
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < count; i++) {
				sb.append(note);
			}
			listener.print(sb.toString());
		}
	}[/color]   //主要实现方法,为什么不红了???

	@Override
	public void run() {
		returnResult(note, count);
	}
}

package com.bjz;

public class Test {
	public static void main(String[] args) {
		for (int i=0;i<10;i++) {
			Reciver reciver = new Reciver(i+"", 50);
			reciver.srtartCallbackThread();
		}
	}
}


测试类

你可能感兴趣的:(code,线程基础)