我有一个很棘手的问题希望大侠们帮助。为了把问题说的清楚些,我贴图:
程序原来是单线程的,main thread 先执行。然后用for循环将sub thread 1-6 依次执行。然后main thread 继续执行。
在1-6 每一个method都有返回值(true and false),任何一个返回false时候,main thread 都会停止。为了提高上面的运行速度,我试图用多线程 将1-6 都用一个线程来执行。 主线程指向第一横线的位置,停止,并开6个线程。然后检查者6个线程的返回状态,如果都返回true,主线程继续执行,如果任意一个线程饭后false。主线程都会停止。希望大侠们能给我提供写解决方案
程序原来是单线程的,main thread 先执行。然后用for循环将sub thread 1-6 依次执行。然后main thread 继续执行。
在1-6 每一个method都有返回值(true and false),任何一个返回false时候,main thread 都会停止。为了提高上面的运行速度,我试图用多线程 将1-6 都用一个线程来执行。 主线程指向第一横线的位置,停止,并开6个线程。然后检查者6个线程的返回状态,如果都返回true,主线程继续执行,如果任意一个线程饭后false。主线程都会停止。希望大侠们能给我提供写解决方案
private ThreadMgr mgr;
private String threadName;
public Task(ThreadMgr mgr , String threadName) {
this.mgr = mgr;
this.threadName = threadName;
}
public String getThreadName() {
return threadName;
}
public abstract void run();
public void setBlock() {
mgr.setBlock(true);
}
}
task就是用来创建 sub thread 1-6 ,并将返回状态返回给 ThreadMgr 。
List<Thread> threadList = new ArrayList<Thread>();启动所有的子线程public void execute() throws Exception {
for (Thread task : threadList) {
task.start();
}}检查状态
public void execute() throws Exception {
for (Thread task : threadList) {
task.start();
}
if(block) {
return;
}
Thread.sleep(20);
while (true) {
if(block) {
break;
}
if(threadList.size() == 0) {
break;
} Thread.sleep(1);
Iterator<Thread> IT = threadList.iterator();
while (IT.hasNext()) {
Thread task = IT.next();
//代表线程结束,从list中删除
if (task.getState() == Thread.State.TERMINATED) {
IT.remove();
}
}
}
}
?那我想贴图如何办?
我的心啊。凉啊。
一定要注意,单线程的代码是否可以并行处理。
若将单一线程的代码,分六个子线程,每个都执行一遍,那就没啥意思了。
其次,我这里采用线程池,按楼主思路编了一个代码,楼主可以参考一下。
package houlei.csdn.java.util.concurrent;import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
*
* @author 侯磊
*/
public class MainThread {
/**
* 一个任务要分成六个线程并发处理。
*/
private static final int nThreads = 6;
static class SubTask implements Callable<Boolean>{
private boolean result ;
private static volatile java.util.Random rand = new java.util.Random(System.currentTimeMillis());
public SubTask(boolean result){this.result=result;}
/**
* 六个子任务的实现内容。(六个线程,执行的内容应该不是相同的)
*/
public Boolean call() throws Exception {
long delay = rand.nextInt(3000);
System.out.println(Thread.currentThread().getName()+" get "+result+" result and delay "+delay+" ms.");
Thread.sleep(delay);
return result;
}
} public static void main(String args []) throws InterruptedException, ExecutionException{
//之前的代码放在before方法体中
before();
//记录核心代码的运行起止时间
long time = System.currentTimeMillis();
//创建六个子线程的执行代码对象
List<Callable<Boolean>> subTasks = getTasks();
//创建线程池,用于执行上述的代码对象
ExecutorService pool = Executors.newFixedThreadPool(nThreads);
//执行代码,获得Future对象,用于判断上述代码对象的执行结果
List<Future<Boolean>> futures = pool.invokeAll(subTasks);
//判断上述代码对象的执行结果
boolean allTrue = awaitFutures(futures);
//关闭线程池。(即使有没有执行完的线程,也依然关闭)
pool.shutdownNow();
//打印核心代码的运行时间。(该时间只是一个大概的时间)
System.out.println("running "+(System.currentTimeMillis()-time)+" ms.");
//之后的代码可放在after方法中。参数allTrue表示上述六个线程的执行结果,是全TRUE还是有一个FALSE。
after(allTrue);
}
private static void before(){}
private static void after(boolean allTure){}
private static List<Callable<Boolean>> getTasks(){
List<Callable<Boolean>> subTasks = new ArrayList<Callable<Boolean>>(nThreads);
subTasks.add(new SubTask(false));
subTasks.add(new SubTask(true));
subTasks.add(new SubTask(true));
subTasks.add(new SubTask(true));
subTasks.add(new SubTask(true));
subTasks.add(new SubTask(true));
return subTasks;
}
private static boolean awaitFutures(List<Future<Boolean>> futures) throws InterruptedException, ExecutionException{
boolean checking = true;
while(checking){
int count = 0;
for(Future<Boolean> f : futures){
if(f.isDone()){
if(f.get()){
count++;
}else {
return false;
}
}
}
if(count==futures.size())return true;
Thread.sleep(10);
}
return false;
}}
但是我还是有一点不明白,你们所说的单线程是否有浪费时间再等待状态与单线程的代码是否可以并行处理,这指的是什么?可以理解成代码里有Thread.sleep(),才有必要进行多线程的处理吗?如果没有sleep,作多线程在速度上没有提升了.
我给一段示例代码,你将就着看。 public void start() throws InterruptedException {
final int[] arr = {0};
int x = arr[0];
Test[] t = new Test[6];
synchronized (arr) {
//synchronized 放在 for 之前保证当前线程首先获得锁。
for (int i = 0; i < t.length; i++) {
t[i] = new Test(arr);
new Thread(t[i]).start();
}
while (arr[0] < t.length) {
arr.wait();
if (arr[0] == x) {
for (int i = 0; i < t.length; i++) {
t[i].stop();
}
return;
}
x = arr[0];
}
}
} private static class Test implements Runnable { public Test(int[] arr) {
this.arr = arr;
} public void run() {
//
boolean runResult = true;
synchronized (arr) {
arr[0] += runResult ? 1 : 0;
arr.notify();
}
} private void stop() {
}
private final int[] arr;
}
Test[] t = new Test[6];
final int[] arr = {0, 0};
for (int i = 0; i < t.length; i++) {
t[i] = new Test(arr);
new Thread(t[i]).start();
}
synchronized (arr) {
while (arr[0] < t.length) {
if (arr[1] > 0) {
for (int i = 0; i < arr.length; i++) {
t[i].stop();
}
return;
}
arr.wait();
}
}
//
} private static class Test implements Runnable { public Test(int[] arr) {
this.arr = arr;
} public void run() {
//
boolean runResult = true;
synchronized (arr) {
arr[runResult ? 0 : 1]++;
arr.notify();
}
} private void stop() {
}
private final int[] arr;
}