并行的世界
1、同步(Synchronous)和异步(Asynchronous)
同步:同步方法调用一旦开始,调用者必须等到方法调用返回后,才能继续后续的行为。
异步:像是一个消息的传递,一旦开始,方法就立即返回,调用者可以继续后续的操作。
2、并发(Concurrency)和并行(Parallelism)
并发和并行都可以表示两个或者多个任务一起执行,但是并发偏重多个任务交替执行(还可能是串行的),并行是真正意义上的“同时执行”
3、临界区
一种公共资源或者说共享数据,可以被多个线程使用。但是每一次只能由一个线程使用它,一旦临界区资源被占用,其他线程想要使用这个资源就必须等待。
4、阻塞(Blocking)和非阻塞(Non-Blocking)
阻塞:等待临界区的资源而导致的线程被挂起。
非阻塞:没有一个线程可以妨碍其他线程的执行。
5、死锁(Deadlock)、饥饿(Starvation)和活锁(Livelock)
都是属于多线程的活跃性问题,
死锁:互相占用对方所需要的资源,导致线程永远的等待下去。
饥饿:某一个或者多个线程因为种种原因无法获得所需要的资源,导致一直无法执行。
并行搜索
package multithreading;
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;
import java.util.concurrent.atomic.AtomicInteger;
public class Search {
static int[] arr;
static ExecutorService pool = Executors.newCachedThreadPool();
static final int Thread_Num = 2;
static AtomicInteger result = new AtomicInteger(-1);
public static int search(int searchValue, int beginPos, int endPos) {
int i = 0;
for (i = beginPos; i < endPos; i++) {
if (result.get() >= 0) {
return result.get();
}
if (arr[i] == searchValue) {
// 如果设置失败,表示其他线程已经找到了
if (!result.compareAndSet(-1, i)) {
return result.get();
}
return i;
}
}
return -1;
}
// 定义一个线程,调用前面的查找
public static class SearchTask implements Callable<Integer> {
int begin, end, searchValue;
public SearchTask(int searchValue, int begin, int end) {
this.searchValue = searchValue;
this.begin = begin;
this.end = end;
}
@Override
public Integer call() throws Exception {
int re = search(searchValue, begin, end);
return re;
}
}
public static int pSearch(int searchValue) throws InterruptedException, ExecutionException {
int subArrsize = arr.length / Thread_Num + 1;
List<Future<Integer>> re = new ArrayList<>();
for (int i = 0; i < arr.length; i += subArrsize) {
int end = i + subArrsize;
if (end >= arr.length) {
end = arr.length;
}
re.add(pool.submit(new SearchTask(searchValue, i, end)));
}
for (Future<Integer> future : re) {
if (future.get() >= 0) {
return future.get();
}
}
return -1;
}
public static void main(String[] args) {
arr = new int[100000];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
int num = search(9999, 0, arr.length);
System.out.println("num = " + num);
}
}