多线程相关知识
两个线程进行通信:通过等待(wait)唤醒(notify)机制
三个或三个以上线程进行通信:通过notifyAll()方法
/*
* 1. 在同步代码块中,用哪个对象锁,就用哪个对象调用wait方法
* 2. 为什么wait和notify方法定义在Object类中?
* 因为锁对象可以是任意对象,而Object类是所有类的基类,所以wait和notify方法定义在Object类中
* 3. sleep和wait的区别:
* 1)sleep方法必须传入时间参数,时间到了自动醒来
* 2)waot方法可传入参数也可不传,传入参数是指时间到了继续等待,不传入参数就直接等待
* 3)sleep方法在同步函数或者同步代码块中不释放锁,睡着了也要抱着锁睡
* 4)wait方法在同步函数或者同步代码块中不释放锁
*
* 4. notify和notifyAll的区别:
* notify:随机唤醒单个等待线程
* notifyAll:唤醒所有等待的线程
* */
通过ReentrantLock互斥锁来实现多个线程通信:
线程的生命周期:
线程池:
1. 程序启动一个新线程的成本是比较高的,因为它涉及到要与操作系统进行交互,而使用线程池能够提高性能
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(2);
es.submit(new myRunnable());
es.submit(new myRunnable());
es.shutdown();
}
}
class myRunnable implements Runnable{
@Override
public void run() {
for(int i = 0; i < 100; i++){
System.out.println(Thread.currentThread().getName() + "..."+i);
}
}
}
利用callable来创建多线程:
import java.util.concurrent.*;
public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(2);
Future<Integer> f1 = es.submit(new myCallable(100));
Future<Integer> f2 = es.submit(new myCallable(500));
System.out.println(f1.get());
System.out.println(f2.get());
es.shutdown();
}
}
class myCallable implements Callable<Integer>{
private int num;
public myCallable(int num){
this.num = num;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for(int i = 0; i <= num; i++){
sum+=i;
}
return sum;
}
}