进程 VS 线程
并发 VS 并行
线程4种实现方法:
1.Thread
2.Runnable
3.FutureTask+Callable
4.使用线程池
启动线程用cat.start() 为什么不是 cat.run()
原因:
cat.run是一个普通的方法,没有真正启动一个线程,就会把run方法执行完毕,才向下执行
真正实现多线程的是private native void start0();
源码分析:
start() -> start0(),线程并不一定立马执行,只是将线程变为可运行状态
private native void start0();
用户线程 VS 守护线程
守护线程当用户线程都运行结束后自动结束,如垃圾回收
只要其它非守
护线程运行结束了,即使守护线程的代码没有执行完,也会强制结束
thread.setDaemon(true);
线程API层面的7种状态:NEW RUNNABLE BLOCKED WAITING TIMED_WAITING TERMINATED
NEW 线程刚被创建,但是还没有调用 start() 方法
RUNNABLE 当调用了 start() 方法之后,Java API 层面的 RUNNABLE 状态涵盖了 操作系统 层面的
【可运行状态】、【运行状态】和【阻塞状态】
BLOCKED , WAITING , TIMED_WAITING 都是 Java API 层面对【阻塞状态】的细分
TERMINATED 当线程代码运行结束
public class TestState {
public static void main(String[] args) throws IOException {
Thread t1 = new Thread("t1") {
@Override
public void run() {
}
};
Thread t2 = new Thread("t2") {
@Override
public void run() {
while (true) {
}
}
};
t2.start();
Thread t3 = new Thread("t3") {
@Override
public void run() {
synchronized (TestState.class) {
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t3.start();
Thread t4 = new Thread("t4") {
@Override
public void run() {
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t4.start();
Thread t5 = new Thread("t5") {
@Override
public void run() {
synchronized (TestState.class) {
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t5.start();
Thread t6 = new Thread("t6") {
@Override
public void run() {
}
};
t6.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t1 state:" + t1.getState());
System.out.println("t2 state:" + t2.getState());
System.out.println("t3 state:" + t3.getState());
System.out.println("t4 state:" + t4.getState());
System.out.println("t5 state:" + t5.getState());
System.out.println("t6 state:" + t6.getState());
}
}
public class Test {
public static void main(String[] args) {
Cat cat = new Cat();
cat.start();
Dog dog = new Dog();
Thread thread = new Thread(dog);
thread.start();
System.out.println("main主线程启动子线程,main主线程不会阻塞,会继续执行,主线程结束不影响子线程,主线程名:" + Thread.currentThread().getName());
}
}
class Cat extends Thread {
@Override
public void run() {
while (true) {
System.out.println("喵喵喵~ " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Dog implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("汪汪汪~ " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
总结:
Runnable是一个函数式接口,实现里面的run()抽象方法,表示线程要执行的任务
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
public class ThreadTest_ {
public static void main(String[] args) {
new Thread("thread1") {
@Override
public void run() {
System.out.println("thread1");
}
}.start();
Runnable task1 = new Runnable() {
@Override
public void run() {
System.out.println("thread2");
}
};
new Thread(task1, "thread2").start();
Runnable task2 = () -> System.out.println("thread3");
new Thread(task2, "thread3").start();
new Thread(() -> System.out.println("thread4"), "thread4").start();
}
}
FutureTask接受一个Callable
public FutureTask(Callable<V> callable)
Callable是一个函数式接口,和Runnable类似,多了返回值和抛异常
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
FutureTask<Integer> task3 = new FutureTask<>(() -> {
System.out.println("thread5");
return 100;
});
new Thread(task3, "thread5").start();
System.out.println(task3.get());
public class Test {
public static void main(String[] args) throws InterruptedException {
Cat cat = new Cat();
cat.setName("cat");
cat.setPriority(1);
cat.start();
System.out.println("main主线程启动子线程,main主线程不会阻塞,会继续执行,主线程结束不影响子线程,主线程名:" + Thread.currentThread().getName());
Thread.sleep(2 * 1000);
cat.interrupt();
cat.join();
System.out.println("join相当于插队到main线程中来,cat线程执行完毕后才执行主线程");
}
}
class Cat extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("喵喵喵~ " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("线程被中断~");
}
}
}
}
1.start() vs run()
public class Start_ {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("running...");
}, "thread1");
System.out.println(thread.getState());
thread.run();
System.out.println(thread.getState());
}
}
2.sleep() vs yield()
sleep 会让当前线程从 Running 进入 Timed Waiting 状态(阻塞)
其它线程可以使用 interrupt 方法打断正在睡眠的线程
建议用 TimeUnit 的 sleep 代替 Thread 的 sleep 来获得更好的可读性
yield 会让当前线程从 Running 进入 Runnable 就绪状态态,然后调度执行其它线程
A hint to the scheduler,具体的实现依赖于操作系统的任务调度器
public class Sleep_ {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
System.out.println("会抛出 InterruptedException");
e.printStackTrace();
}
}, "thread1");
thread1.start();
Thread.sleep(500);
thread1.interrupt();
}
}
3.Priority
java中规定线程优先级是1~10的整数,较大的优先级
能提高该线程被 CPU 调度的机率
public class Priority_yield {
public static void main(String[] args) {
Runnable task1 = () -> {
int count = 0;
for (;;) {
System.out.println("---->1 " + count++);
}
};
Runnable task2 = () -> {
int count = 0;
for (;;) {
System.out.println(" ---->2 " + count++);
}
};
Thread t1 = new Thread(task1, "t1");
Thread t2 = new Thread(task2, "t2");
t1.start();
t2.start();
}
}
4.join()
public class Join_ {
private static int a = 0;
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
try {
a = 10;
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "thread1");
thread1.start();
thread1.join();
System.out.println("a = " + a);
}
}
5.interrupt
如果被打断线程正在 sleep,wait,join 会导致被打断
的线程抛出InterruptedException,isInterrupted=false
如果正在运行的线程、park的线程被打断,isInterrupted=true
LockSupport.park()和LockSupport.unpark()实现线程的阻塞和唤醒
park()和unpark()不会遇到Thread.suspend 和 Thread.resume所可能引发的死锁问题
信号量permit默认是0,累加上限是1,park()消费permit,unpark()生成permit
interrupt()会使得中断状态为true,并调用unpark
如果打断标记已经是 true, 则 park 会失效,可以使用 Thread.interrupted() 清除打断状态
interrupt()、interrupted()和isInterrupted()方法详解
interrupt():中断线程,sleep,wait,join 会导致被打断
的线程抛出InterruptedException,正在运行的线程只是给线程设置一个中断标志,线程仍会继续运行
interrupted():测试当前线程是否被中断,并清除中断状态
isInterrupted():测试此线程是否被中断
6.过时的方法 stop()停止线程、suspend()挂起线程、resume()恢复线程,容易破坏同步代码块,造成线程死锁
释放锁:
1.同步方法、同步代码块正常执行结束,或遇到return、break
2.同步方法、同步代码块异常结束,出现Error或Exception
3.调用wait()方法,当前线程暂停执行并释放锁
不释放锁:
1.调用sleep()、yield()方法,当前线程暂停执行并不释放锁
2.线程执行同步代码块时,其他线程调用该线程的suspend()方法将线程挂起,该线程不释放锁。
提示:避免使用suspend()和resume()控制线程,方法不再推荐使用
可在用在方法上(同步方法)、代码块(同步代码块),要求多个线程的锁对象是同一个
private synchronized static void sell() {
}
private synchronized void sell() {
}
synchronized (对象) {
}
public class Syncronized_ {
public static void main(String[] args) {
Cat cat1 = new Cat();
cat1.start();
Cat cat2 = new Cat();
cat2.start();
}
}
class Cat extends Thread {
static int ticketNum = 10;
static boolean loop = true;
@Override
public void run() {
while (loop) {
sell();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void sell() {
if (ticketNum > 0) System.out.println(Thread.currentThread().getName() + "卖票:" + ticketNum--);
else loop = false;
}
}
修改如下:
方式一:同步方法(静态)的锁对象默认为 当前类.class
private synchronized static void sell() {
if (ticketNum > 0) System.out.println(Thread.currentThread().getName() + "卖票:" + ticketNum--);
else loop = false;
}
方式二:代码块上锁,指定同一个锁对象
private void sell() {
synchronized (Syncronized_.class) {
if (ticketNum > 0) System.out.println(Thread.currentThread().getName() + "卖票:" + ticketNum--);
else loop = false;
}
}
方式三:同步方法(非静态)的锁对象默认为 this
public class Syncronized_ {
public static void main(String[] args) {
Cat cat = new Cat();
new Thread(cat).start();
new Thread(cat).start();
}
}
class Cat implements Runnable {
static int ticketNum = 10;
static boolean loop = true;
@Override
public void run() {
while (loop) {
sell();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void sell() {
if (ticketNum > 0) System.out.println(Thread.currentThread().getName() + "卖票:" + ticketNum--);
else loop = false;
}
}