静态方法 sleep yield函数
抛中断异常
废弃函数 stop、suspend()
join
SetPriority
newFixedThreadPool(numberOfThreads:
int): ExecutorService
创建n个线程,线程可以重复使用
+newCachedThreadPool():
ExecutorService
空闲的线程超时了,会回收线程(适合短任务,量大的线程)
任务就是对象
public class TaskClass Implements Runnable
创建任务--实现Runable 接口
创建任务:TaskClass task =new TaskClass()
创建任务线程: Thread thread=new Thread(task)
线程运行(start方法会导致run方法被执行): thread.start()
Thread类:(实现了Runable接口)
public class myThread extends Thread{
}
join方法使得一个线程等待另一个线程的结束
优先级1-10 越高越先执行
线程池:
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(() -> System.out.println("hello"));
executor.execute(() -> System.out.println("hello2"));
executor.shutdown();
线程同步:
关键字同步:
public synchronized void depoist(double amount)
public void depoist(double amount) {
synchronized (this) {
.....
}
利用加锁同步:
public static Lock lock=new ReentrantLock(); //creat a lock;
public void test() {
lock.lock();
int a=2;
lock.unlock();
}
线程间协作:
Lock对象的newCondition方法:
await() 让当前线程进入等待
signal/signalAll() 唤醒一个/所有的等待线程
监视器:
wait() 释放锁进入等待
notify/notifyAll() 通知一个/所有的线程重新获取锁恢复执行