Thread 的基本介绍和 Synchronized 常见注意事项
一、State 类型
1、操作系统线程 State
新建(new):创建了一个新的线程对象
就绪(runnable):调用线程的 start()方法,处于就绪状态
运行(running):获得了 CPU 时间片,执行程序代码,就绪状态是进入到运行状态的唯一入口
阻塞(block): 线程放弃对 CPU 的使用权,停止执行,直到进入就绪状态在有可能再次被 CPU 调度
等待阻塞:运行状态的线程执行 wait 方法,JVM 会把线程放在等待队列中,使本线程进入阻塞状态。
同步阻塞:线程在获得 synchronized 同步锁失败,JVM 会把线程放入锁池中,线程进入同步阻塞。对于锁池和等待池,可以看这篇文章
其他阻塞:调用线程的 sleep()或者 join()后,线程会进入道阻塞状态,当 sleep 超时或者 join 终止或超时,线程重新转入就绪状态
死亡(dead):线程 run()、main()方法执行结束,或者因为异常退出了 run()方法,则该线程结束生命周期
2、Java 线程 State
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| public enum State {
NEW,
RUNNABLE,
BLOCKED,
WAITING,
TIMED_WAITING,
TERMINATED; }
|
二、创建线程的方法
1、继承 Thread
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class ThreadDemo{ public static void main(String[] args) { MyThread myThread=new MyThread(); myThread.start(); for (int i = 0; i < 100; i++) { System.out.println("我是主线程"+i); } } } class MyThread extends Thread{ public void run(){ for(int i=0;i<100;i++){ System.out.println("我是线程"+i); } } }
|
2、实现 Runable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class RunnableDemo { public static void main(String[] args) { MyRunnale mr=new MyRunnale(); new Thread(mr).start(); for (int i = 0; i < 1000; i++) { System.out.println("我是主线程"+i); } } }
class MyRunnale implements Runnable{ @Override public void run() { for (int i = 0; i < 1000; i++) { System.out.println("我是线程"+i); } } }
|
3、实现 Callable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
public class ThreadNew { public static void main(String[] args) { NumThead m=new NumThead();
FutureTask futureTask = new FutureTask(m); new Thread(futureTask).start();
try { Object sum = futureTask.get(); System.out.println("总和是:"+sum); } catch (Exception e) { e.printStackTrace(); } }
}
class NumThead implements Callable{ @Override public Object call() throws Exception { int sum=0; for(int i=1;i<=100;i++){ System.out.println(i); sum+=i; } return sum; } }
|
4、线程池
三、同步问题及解决
1、多线程同步问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public class SellTicket implements Runnable { private int tickets=100; public void run(){ while (true){ if(tickets>0){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"正在出售第"+tickets--+"张票"); }else{ } } } } @SuppressWarnings("all") public class SellTicketDemo { public static void main(String[] args) { SellTicket st = new SellTicket(); Thread t1 = new Thread(st, "窗口1"); Thread t2 = new Thread(st, "窗口2"); Thread t3 = new Thread(st, "窗口3"); t1.start(); t2.start(); t3.start(); } }
|
2、同步锁
synchronized 同步锁,对 this 和 class 的效果是不一样的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| public class SellTicket implements Runnable { private int tickets = 100; private Object obj = new Object(); private int x = 0;
@Override public void run() { while (true) { if (x % 2 == 0) { synchronized (this) { if (tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票"); tickets--; } } } else { sellTicket(); } x++; } }
private synchronized void sellTicket() { if (tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票"); tickets--; } } }
|
3、虚假唤醒
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| package github.polarisink.sync;
public class Test { public static void main(String[] args) { Food noodles = new RegularNoodles(); new Thread(() -> { try { for (int i = 0; i < 10; i++) { noodles.makeNoodles(); } } catch (InterruptedException e) { e.printStackTrace(); } }, "厨师A").start(); new Thread(() -> { try { for (int i = 0; i < 10; i++) { noodles.makeNoodles(); } } catch (InterruptedException e) { e.printStackTrace(); } }, "厨师B").start(); new Thread(() -> { try { for (int i = 0; i < 10; i++) { noodles.eatNoodles(); } } catch (InterruptedException e) { e.printStackTrace(); } }, "食客甲").start(); new Thread(() -> { try { for (int i = 0; i < 10; i++) { noodles.eatNoodles(); } } catch (InterruptedException e) { e.printStackTrace(); } }, "食客乙").start(); } }
class RegularNoodles implements Food { private int num = 0; @Override public synchronized void makeNoodles() throws InterruptedException { if (num != 0) { this.wait(); } num++; System.out.println(Thread.currentThread().getName() + "做好了一份面,当前有" + num + "份面"); this.notifyAll(); } @Override public synchronized void eatNoodles() throws InterruptedException { if (num == 0) { this.wait(); } num--; System.out.println(Thread.currentThread().getName() + "吃了一份面,当前有" + num + "份面"); this.notifyAll(); } }
class HandRolled implements Food { private int num = 0; @Override public synchronized void makeNoodles() throws InterruptedException { while (num != 0) { this.wait(); } num++; System.out.println(Thread.currentThread().getName() + "做好了一份面,当前有" + num + "份面"); this.notifyAll(); } @Override public synchronized void eatNoodles() throws InterruptedException { while (num == 0) { this.wait(); } num--; System.out.println(Thread.currentThread().getName() + "吃了一份面,当前有" + num + "份面"); this.notifyAll(); } } interface Food {
void makeNoodles() throws InterruptedException;
void eatNoodles() throws InterruptedException; }
|