日期:2014-05-18  浏览次数:20634 次

java concurrent多线程

import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyExecutor extends Thread {
String name;

public MyExecutor(String s) throws MalformedURLException, RemoteException,
NotBoundException {
this.name = s;
}

public void run() {
try {
System.out.println(Thread.currentThread().getName());
System.out.println(" start....");
System.out.println(name);
System.out.println("result:" + s);
Thread.sleep((int) (Math.random() * 1000));
System.out.println(" end...");
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String args[]) throws MalformedURLException,
RemoteException, NotBoundException {
ExecutorService service = Executors.newFixedThreadPool(4);

Queue<String> allTasks = new ConcurrentLinkedQueue<String>();
allTasks.offer("1111");
allTasks.offer("2222");
allTasks.offer("3333");
allTasks.offer("4444");
allTasks.offer("5555");
allTasks.offer("6666");

String str;

while ((str = allTasks.poll()) != null) {
service.execute(new MyExecutor(str));
System.out.println(str);
}

System.out.println("submit finish");
service.shutdown();
}
}


上述代码是用concurrent包写了个多线程,请问下有什么问题没?

------解决方案--------------------
目测没啥问题,LZ想测什么场景呢?CPU处理速度很快的,你的简单线程也许一execute就完成了,不会超出队列的。
------解决方案--------------------
引用:
目测没啥问题,LZ想测什么场景呢?CPU处理速度很快的,你的简单线程也许一execute就完成了,不会超出队列的。

不好意思,没注意还有句:Thread.sleep((int) (Math.random() * 1000));
这样就会超过4个线程了,呵呵
------解决方案--------------------
System.out.println("result:" + name);
------解决方案--------------------
关键是你要问什么问题?遇到什么不对或不理解的问题

------解决方案--------------------
引用:
现在有个问题就是在线程中调用外部方法,这个方法会返回个字符串("true"或"false"),如果为false的话,要停止队列的循环,该如何实现?


你是要停止队列循环,加个voliate isRunning=true的标志就行了啊

while(isRunning&&xxxxx){
....
}
当你的线程返回字符串为false时,改变isRunning=false则可以停止掉你队列的循环。

ps:楼主这里最好将allTasks.poll放到while循环里面,这里你的while条件来看,你的程序在跑完线程后,自动就会结束掉你的队列循环。


还有一种停止掉你队列的循环是,在你的线程中加入一个结束消息,例如结束消息为str="End"
然后再你的循环中每次去判断
if("End".equals(result)){
break;