由于才疏学浅,只能管理项目中的一个类似webservice 模块 API,这几天学java,就无聊吧项目的代码看了下。
实现很简单,就是一个观察者模式,但是经常down,不管怎么 先上代码吧。
1.是一个后台观察类,由于是API,要一直起着监听被观察者干完活没有
package test;
import java.util.Observable;
import java.util.Observer;
public class TestThread implements Observer{
private String name;
public TestThread(String name){
this.name = name;
}
public void init(){
System.out.println("this is init.....");
}
public static void main(String[] args) throws InterruptedException {
TestThread test = new TestThread("Task1");
test.init();
synchronized (test) {
test.wait();
}
}
@Override
public void update(Observable o, Object task) {
// TODO Auto-generated method stub
System.out.println("this is task name:"+(String)task);
}
}
当然是实现了 observer。 这个管理类 利用线程同步,的wait的方法,来获取后台的每个task
2.被观察者。
package test;
import java.util.Observable;
public class NotifyTestThread extends Observable{
private TestThread test = new TestThread("manager");
public void setComplement(TaskThread taskThread,String task){
this.addObserver(test);
this.setChanged();
this.notifyObservers(task);
}
}
被观察者继承 observable ,其中3个重要的方法,(1)加观察者(2)保存修改(3)通知观察者。这里 引进一个一个线程变量,后台的任务线程调用这个方法。每个线程结束或者怎么地,就调用这个被观察者类的方法,然后通知观察者来搞着搞那。
3.线程
package test;
import java.util.Random;
public class TaskThread extends Thread{
private NotifyTestThread notify = new NotifyTestThread();
private String task ;
public TaskThread(String task){
this.task = task;
}
public void run(){
try {
System.out.println("this is task:"+task);
this.sleep(new Random().nextInt(1000));
notify.setComplement(this,task);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
TaskThread thread1 = new TaskThread("task1");
TaskThread thread2 = new TaskThread("task2");
TaskThread thread3 = new TaskThread("task3");
thread1.start();
thread2.start();
thread3.start();
}
}
具体的线程任务类,哎 项目没有用Spring ,这就是伪代码。最后观察者一直在等后面的任务是不是完成,后面线程就做一个报告一个。。也算是学习了,
哎 这几天一直在学java,java水太深了。。。学了快一个月了!加油!!!!!另外,如果有人看到这个,谁能教我学那个持久层框架好。最近看hibernate 感觉太乱了。。。难道是老了么 学习能力下降了。。额 。。
闲来无聊,看看项目的代码。自己写了一个伪代码。好好学java!
猜你喜欢
转载自zhanghaj00.iteye.com/blog/2026044
今日推荐
周排行