第一次玩多线程,看代码。
public class Test {
public static void doSomthing(){
System.out.println("11111111111");
}
public static void main(String[] args) {
System.out.println("调用线程1方法...");
TestThread1 testThread1 = new TestThread1();
testThread1.doSomething();
System.out.println("调用线程2方法...");
TestThread2 testThread2 = new TestThread2();
testThread2.doSomething();
System.out.println("其他方法.....");
doSomthing();
}
}
需求是:main里面的3个方法,要按顺序执行。
public class TestThread1 implements Runnable{
public void doSomething(){
ThreadPool pool = new ThreadPool();
for (int i = 0; i < 10; i++) {
pool.addThread(new TestThread1());
}
pool.shutdonw();
}
public void run() {
System.out.println("这是线程1...");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
TestThread1 和 TestThread2 是一样的。
public class ThreadPool {
private Integer POOL_SIZE = 2;
private ExecutorService pool = Executors.newFixedThreadPool(POOL_SIZE);
private ThreadCallback callback = null;
private ThreadMonitor monitor = null;
public ThreadPool() {
}
public synchronized void addThread(Runnable thread) {
pool.execute(thread);
}
public synchronized void setCallback(ThreadCallback callback) {
if (monitor == null) {
this.callback = callback;
monitor = new ThreadMonitor(pool, callback);
Thread thread = new Thread(monitor);
thread.start();
}
}
public synchronized void shutdonw() {
pool.shutdown();
}
public synchronized boolean isTerminated() {
return pool.isTerminated();
}
}
ThreadPool是别人写的,
求大神啊!~~
需求是:main里面的3个方法,要按顺序执行。
就是
testThread1.doSomething();
完成后执行testThread2.doSomething();
完成后执行doSomthing();