1.Callable
implements Callable
MyCallable a = new MyCallable();
FutureTask futureTask = new FutureTask(a);
new Thread(futureTask).start();
Object o = futureTask.get();
System.out.println(o);
2.lock
lock.lock();
lock.unlock();
synchronized
Thread的synchronized方法要加static
3.Runnable
implements Runnable
MyRunnable thread = new MyRunnable();
Thread t1 = new Thread(thread);
t1.setName("Runnable");
t1.start();
4.Thread
extends Thread
MyThread thread = new MyThread();
thread.start();
5.ThreadPool
//corePoolSize:核心池的大小
//maximumPoolSize:最大线程数
//keepAliveTime:线程没有任务时最多保持多少时间后会终止
ExecutorService service = Executors.newFixedThreadPool(10);//设置线程池大小
//设置线程池的属性
ThreadPool service1 = (ThreadPool) service;
// service1.setThreadPool();
service.execute(new MyRunnable());//适用于Runnable
service.submit(new MyCallable());//适用于Callable
service.shutdownNow();//关闭线程池
6.方法
getName():获取线程名,在main要Thread.currentThread().getName()
currentThread():返回当前线程
yield():释放当前cpu的执行权力
join():在线程A中调用线程B的join,A会进入阻塞状态,一直到B执行完,A才会结束阻塞
sleep():睡眠
isAlive():判断当前线程是否存活
getPriority():返回线程的优先级
wait():一旦执行此方法,当前线程就会进入阻塞状态,并释放同步监视器
notify():一旦执行此方法,就会唤醒被wait的一个线程,如果有多个线程被wait,就先唤醒优先级高的哪一个
notifyAll():一旦执行此方法,唤醒所有被wait的线程
wait()、notify()、notifyAll()三个方法必须使用在同步方法块或同步方法中
设置线程的优先等级
MAX_PRIORITY :10
MIN_PRIORITY :1
NORM_PRIORITY :5
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);