1.线程的实现方法
- 继承Thread类:有start方法
- 实现Runnable接口:没有start方法,底层实现模式静态代理
启动方式如下:
public class test {
public static void main(String[] args) throws InterruptedException {
runnableTest test1 = new runnableTest();
Thread thread = new Thread(test);
thread1.run();
threadTest test2 = new threadTest();
test2.start();
}
}
public class threadTest extends Thread{
@Override
public void run(){
System.out.println("2");
}
}
public class runnableTest implements Runnable{
@Override
public void run() {
System.out.println("1");
}
}
public class Thread implements Runnable {
private Runnable target;
public Thread(Runnable target) {
this(null, target, "Thread-" + nextThreadNum(), 0);
}
public void run() {
if (target != null) {
target.run();
}
}
}
3. Thread类实际上也是实现了Runnable接口
4. start 中调用了native方法叫start0,实际上是调用本地方法库中的方法
5. 多线程的实现实际上是start0方法而不是run方法
2. 进程和线程的关系
进程是资源分配的单元
线程:实施调度和分配的基本单元
psvm:main 也是一个线程
3. sychnized关键字
5. notify和notifyall
6. 使用jconsole来监测线程的运行情况
优先级
1. 设置方法:setPriority; 获取方法:getPriority
2. 优先级的设置范围:MAX 10 ; MIN 1; NORM 5;
public class Thread implements Runnable {
public static final int MIN_PRIORITY = 1;
public static final int NORM_PRIORITY = 5;
public static final int MAX_PRIORITY = 10;
private int priority;
public final void setPriority(int newPriority) {
ThreadGroup g;
checkAccess();
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
throw new IllegalArgumentException();
}
if((g = getThreadGroup()) != null) {
if (newPriority > g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
setPriority0(priority = newPriority);
}
}
}
优先级低只是代表获得调度的概率低,而并不是就不会被调用了
Interrupt方法
一般用于中断正在休眠的线程
捕获到中断异常InterruptedException
sleep方法
线程的静态方法,释放锁
wait方法
不释放锁
yield方法
线程礼让,让当前线程停止不阻塞
但是礼让不一定成功
join方法
使用join方法将两个本来是随机交替执行的线程变成顺序执行
合并线程,其他线程阻塞
线程的状态
/**
* A thread state. A thread can be in one of the following states:
* <ul>
* <li>{@link #NEW}<br>
* A thread that has not yet started is in this state.
* </li>
* <li>{@link #RUNNABLE}<br>
* A thread executing in the Java virtual machine is in this state.
* </li>
* <li>{@link #BLOCKED}<br>
* A thread that is blocked waiting for a monitor lock
* is in this state.
* </li>
* <li>{@link #WAITING}<br>
* A thread that is waiting indefinitely for another thread to
* perform a particular action is in this state.
* </li>
* <li>{@link #TIMED_WAITING}<br>
* A thread that is waiting for another thread to perform an action
* for up to a specified waiting time is in this state.
* </li>
* <li>{@link #TERMINATED}<br>
* A thread that has exited is in this state.
* </li>
* </ul>
**/
守护(daemon)线程
线程分为用户线程(虚拟机确保完成);守护线程(虚拟机不用确保完成)
守护线程例子:后台操作日志,垃圾回收,监控日志
设计守护线程的方法
public final void setDaemon(boolean on) {
checkAccess();
if (isAlive()) {
throw new IllegalThreadStateException();
}
daemon = on;
}
Synchronized关键字
两种实现方式:Synchronized方法;Synchronized代码块
Lock
接口:java.utils.concurrent.locks.Lock
接口的实现类:ReentrantLock