并发库学习笔记一
新建线程并启动的几种方法:
1
private Thread thread=new Thread("myThread");
Thread.start();
2
private class myThread extends Thread {
@Override
public void run() {
}
}
myThread thread=new myThread().start();
3
private Thread thread = new Thread() {
//构造器
@Override
public void run() {
}
};
thread.setName("myThread");
Thread.start();
4 Thread thread = new Thread(task);// 传入任务
Thread.start();
5
Thread thread=new Thread(task, "myThread");
Thread.start();
注:线程启动的时候一定要给它命名,以便于后期排错
响应线程中断
程序要对线程的中断作出对应的响应
方法一:
private class myThread extends Thread {
/**
* 构造器
*/
public myThread() {
}
@Override
public void run() {
for (;;) {
// 耗时操作
doxxx();
// 如果线程中断,作出相应操作
if (Thread.interrupted()) {
break;
}
}
}
}
方法二:
方法三:
private class myThread extends Thread {
/**
* 构造器
*/
public myThread() {
}
@Override
public void run() {
for (;;) {
try {
doxxx();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
ThreadLocal (线程局部变量) 作用就是为每个使用变量线程提供一个变量的副本
这样每个线程都可以改变自已的线程
使用线程局部变量一般定义在表态变量
注:如果没有调用remove方法,将会使内存溢出
任务的提交者和执行者
利用Executors这个工厂类来生产自已需要的executor
executorService = Executors.newFixedThreadPool(10);
任务的提交者和执行者之间的通信手段Future
// 单例线程池
executorService = Executors.newSingleThreadExecutor();
class TaskWithResult implements Callable<String> {
@Override
public String call() throws Exception {
String resu = "";
return resu;
}
}
TaskWithResult taskWithResult = new TaskWithResult();
Future<String> future = executorService.submit(taskWithResult);
try {
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Future的几个主要方法:
future.get();//阻塞主任务完成
future.cancel(ture);
Future.get(timeOut);//等待一段时间
线程池Executors中的部分方法
//一个可以重用固定线程数的线程池,以共享的无界队列方式来运行这些线程,
//在需要时可用ThreadFactory创建新线程,在关闭之前,池中的线程将一直 存在
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
//用于创建新线程的默认线程工厂,此工厂创建同一个线程组,如果有securityManager
//则它使用System.getXecurityManager()返回的组
public static ThreadFactory defaultThreadFactory() {
return new DefaultThreadFactory();
}
//创建一个可以根据需要创建新线程的线程池,以前创建的线程可用时就重用它们
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
//它可以在规定延迟后运行命令或定期执行
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
//在未来某个指定的时间执行给定的命令
void execute(Runnable command);
//执行一次顺序关闭,执行一次之前提交的任务,并不接受新任务
void shutdown();
线程的基本控制
thread.interrupt();
thread.sleep(0);
thread.join();
thread.start();
//过时的方法
thread.suspend();
thread.destroy();
thread.stop();
thread.resume();