基本概念

程序————>进程————–>线程

  • 进程
    • 进程就是执行程序的一次执行过程,它是一个动态的概念,式系统资源分配的单位
    • 通常再一个进程中可以包含若干个线程,当然一个进程中至少有一个线程,不然没有存在的意义,线程是CPU调度和执行的单位
  • 线程
    • 线程就是独立的执行路径
    • 在程序运行时,即使没有自己创建线程,后台也会有多个线程,比如主线程,GC线程
    • main()称之为主线程,为系统的入口,用于执行整个程序
    • 在一个进程中,如果开辟了多个线程,线程的运行是由调度器安排调度的,调度器是与操作系统紧密相关的,先后顺序是不能人为干预的
    • 对同一份资源操作时mm会存在资源抢夺的问题,需要加入并发控制
    • 线程会带来额外的开销,如CPU调度时间,并发控制开销
    • 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
  • 多线程

线程创建

Thread—————–>继承Thread类

Runnable————–>实现Runnable接口

Callable—————->实现Callable接口(目前了解)

​ 创建线程的三种方法,推荐实现Runnable接口,第一种继承Thread类实际还是实现了Runnable接口,第三种就是有些复杂,工作可以用,下面就是三种线程创建方法。

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
package demo01;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ThreeThread {
public static void main(String[] args) throws ExecutionException, InterruptedException {

new huang().start();

//new wan().run();
new Thread(new wan()).start();

// 通过实现Callable接口来创建线程的开启方法
FutureTask<Integer> futureTask = new FutureTask<Integer>(new hahaha());
new Thread(futureTask).start();
Integer integer = futureTask.get();
System.out.println(integer);
}
}

// 1.继承Thread类
class huang extends Thread{
@Override
public void run() {
System.out.println("huang这个线程被创建了!!!");
}
}

// 2.实现runnable接口
class wan implements Runnable{
@Override
public void run() {
System.out.println("wan这个线程被创建了!!!");
}
}

// 3.实现Callable接口
class hahaha implements Callable<Integer>{

@Override
public Integer call() throws Exception {
System.out.println("hahaha这个线程被创建了!!!");
return 123;
}
}

小结:

  • 继承Thread类:

    • 子类继承Thread类具备多线程能力
    • 启动线程:子类对象.start()
    • 不建议使用:避免OOP单继承局限性
  • 实现Runnable接口

    • 实现Runnable接口具备多线程能力
    • 启动线程:new Thread(子类对象).start()
    • 推荐使用:避免单继承局限性,方便同一个对象被多个线程使
  • 实现Calleble接口

    • 重写call()方法

    • 创建执行服务

    ExecutorService ser = Executors.newFixedThreadPool(线程数);

    • 提交执行

    Future<返回值类型> r = ser.submit(线程名);

    • 获取结果

    类型 res=r.get();

    • 关闭服务

    ser.shutdownNow();

实现Runnable接口举例如下:

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
package demo01;
//模拟龟兔赛跑
public class TestThread6 implements Runnable{
//胜利设
private static String winner;

@Override
public void run() {
for (int i = 0; i <=101; i++) {
//模拟兔子休息
if (Thread.currentThread().getName().equals("兔子")&& i%20==0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
boolean flag=gameover(i);
//比赛结束,停止
if (flag){
break;
}

System.out.println(Thread.currentThread().getName()+"----->跑了第"+i+"步");

}
}
//判断是否为完成比赛
private boolean gameover(int steps){
//判断是否有胜利者
if (winner!=null){
return true;
}{
if (steps>=101){
winner=Thread.currentThread().getName();
System.out.println("winner is"+winner);
}
}
return false;
}

public static void main(String[] args) {
TestThread6 testThread6 = new TestThread6();
new Thread(testThread6,"兔子").start();
new Thread(testThread6,"乌龟").start();
}
}

静态代理

​ 这里为啥要讲这个静态代理这个尼,因为多线程底层实现就是这个静态代理,下面会给出具体例子来理解静态代理这个概念,总结就是用最简单的例子做出最复杂的功能,以婚庆公司为例,例子: 真实角色:你; 代理角色:婚庆公司; 结婚:实现结婚接口。

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
public class StaticProxy {
public static void main(String[] args) {
WeddingCompany company = new WeddingCompany(new You());
company.happyMarry();
}

}

interface Marry{
void happyMarry();
}

//真实角色
class You implements Marry{

@Override
public void happyMarry() {
System.out.println("结婚了真开心!");

}

}

//代理角色,帮助你结婚
class WeddingCompany implements Marry{

private Marry target;

public WeddingCompany(Marry target){
this.target = target;
}

@Override
public void happyMarry() {
before();
this.target.happyMarry();
after();

}

private void after() {
System.out.println("结婚之后,收尾款");

}

private void before() {
System.out.println("结婚前,布置现场");
}

}

总结:真实对象和代理对象都要实现同一个接口,代理对象要代理真实角色

优点:代理对象可以做很多真实对象不能做的事情,真实对象专注自己的事情

结合线程来看:

new Thread(t).start();

new WeddingCompany(new You()).happyMarry();

  • Runnable ——> Marry 接口

  • Thread —->WeddingCompany 即代理

  • t ——> new You() 目标对象(真实角色)

Lambda表达式

  • 实质属于函数式编程的概念

1.作用

  • 避免匿名内部类定义过多
  • 使代码看起来简介
  • 简化代码,只留下核心逻辑

2.函数式接口

定义:任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口

public interface Runnable{

public abstract void run();

}

对于函数式接口,我们可以通过lambda表达式来创建该接口的对象

3.lambda简单推导

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
package com.lmr.practice;

/**
* 推导Lambda表达式
* @author DELL
*
*/
public class TestLambda {

//3.静态内部类
static class Like2 implements Ilike{

@Override
public void lambda() {
System.out.println("i like lambda2");
}
}

public static void main(String[] args) {
Ilike like = new Like();
like.lambda();

like = new Like2();
like.lambda();

//4.局部内部类
class Like3 implements Ilike{

@Override
public void lambda() {
System.out.println("i like lambda4");
}
}

like = new Like3();
like.lambda();

//5.匿名内部类
like = new Ilike() {

@Override
public void lambda() {
System.out.println("i like lambda5");
}
};

like.lambda();


//6.用lambda简化
like = ()->{
System.out.println("i like lambda5");

};
like.lambda();

}

}

//1.定义一个函数式接口
interface Ilike{
void lambda();
}

//2.实现类
class Like implements Ilike{

@Override
public void lambda() {
System.out.println("i like lambda");

}

}
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
package com.lmr.practice;

public class TestLambda2 {

public static void main(String[] args) {
ILove love = null;
//1.lambda表示简化
love = (int a)->{
System.out.println("LOvee"+ a);
};

//简化1:参数类型
love = (a)->{
System.out.println("LOvee"+ a);
};

//简化2:简化括号
love = a->{
System.out.println("LOvee"+ a);
};

//简化3:简化花括号
love = a-> System.out.println("LOvee"+ a);

love.love(205);
}

}

interface ILove{
void love(int a);
}

总结:

  • lambda表达式只能有一行代码的情况下才能简化成为一行,如果有多行,那么就用代码块包裹。
  • lambda表达式的前提是接口为函数式接口。
  • 多个参数也可以去掉参数类型,要去掉就都去掉,必须加上括号。

线程具体操作

1.线程状态

1

2

2.线程停止的方法

  • 建议线程正常停止——>利用次数,不建议死循环
  • 建议使用标志位——>设置一个标志位
  • 不要使用stop或者destroy等过时或者JDK不建议使用的方法
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
public class TestStop implements Runnable{
//1.设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while(flag){
System.out.println("run...Thread"+ i++);
}
}

//2.设置一个公开的方法停止线程,转换标志位
public void stop(){
this.flag = false;
}

public static void main(String[] args) {
TestStop stop = new TestStop();
new Thread(stop).start();

for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
if(i==900){
//调用stop方法切换标志位,让线程停止
stop.stop();
System.out.println("线程停止了");
}
}
}
}

3.线程休眠 - sleep()

  • sleep(时间)指定当前线程阻塞的毫秒数;
  • sleep存在异常InterruptedException;
  • sleep时间达到后线程进入就绪状态;
  • sleep可以模拟网络延时,倒计时等;
  • 每一个对象都有一个锁,sleep不会释放锁。
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
例子1:模拟延时:TestThread
模拟网络延时的作用:放大问题的发生性
12
package com.lmr.practice;

import java.text.SimpleDateFormat;
import java.util.Date;

//模拟倒计时
public class TestSleep2 {

public static void main(String[] args) {
// try {
// tenDown();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//打印系统当前时间
Date startTime = new Date(System.currentTimeMillis()); //获取系统当前时间
while(true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis()); //更新当前时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void tenDown() throws InterruptedException {
int num = 10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if(num<=0){
break;
}
}
}
}

8.线程礼让 - yield()

  • 礼让线程,让当前正在执行的线程暂停,但不阻塞;
  • 将线程从运行状态转为就绪状态;
  • 让CPU重新调度,礼让不一定成功,看CPU心情。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class TestYield {

public static void main(String[] args) {
MyYield myYield = new MyYield();

new Thread(myYield,"a").start();
new Thread(myYield,"b").start();

}
}

class MyYield implements Runnable{

@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行");
Thread.yield(); //礼让
System.out.println(Thread.currentThread().getName()+"线程停止执行");
}
}

4.线程强制执行 - join()

  • join合并线程,待此线程执行完后,再执行其它线程,其它线程阻塞;
  • 可以想象成插队
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("线程VIP来了"+i);
}
}

public static void main(String[] args) throws InterruptedException {
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);

//主线程
for (int i = 0; i < 1000; i++) {
if(i == 200){
thread.start();
thread.join(); //插队
}
System.out.println("main"+i);

}
}
}

5.观测线程状态

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
public class TestState {

public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("///");
});

//观察状态
Thread.State state = thread.getState();
System.out.println(state); //NEW

//观察后启动
thread.start(); //启动线程
state = thread.getState();
System.out.println(); //Run

while(state != Thread.State.TERMINATED){ //只要线程不停止,就一直输出状态
Thread.sleep(100);
state = thread.getState(); //更新线程状态
System.out.println(state); //输出状态

//thread.start(); 报错,因为已经死亡的线程不能再启动
}
}
}

6.线程的优先级

  • Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级来决定应该调度哪个线程来执行。
  • 线程的优先级用数字表示,范围从1~10.
    • Thread.MIN_PRIORITY = 1;
    • Thread.MAX_PRIORITY = 10;
    • Thread.NORM_PRIORITY = 5;
  • 使用一下方法改变或获取优先级
    • getPriority.setPriority(int xxx)
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
public class TestPriority {
public static void main(String[] args) {
//主线程默认优先级
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());

MyPriority myPriority = new MyPriority();

Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
Thread t5 = new Thread(myPriority);
Thread t6 = new Thread(myPriority);

//先设置优先级,再启动
t1.start();

t2.setPriority(1);
t2.start();

t3.setPriority(4);
t3.start();

t4.setPriority(Thread.MAX_PRIORITY);
t4.start();

// t5.setPriority(-1); //Exception in thread "main" java.lang.IllegalArgumentException
// t5.start();
//
// t6.setPriority(11); //Exception in thread "main" java.lang.IllegalArgumentException
// t6.start();

}

}

class MyPriority implements Runnable{

@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}

总结:优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了。这都看CPU的调度。

7.守护线程

  • 线程分为用户线程守护线程
  • 虚拟机必须确保用户线程执行完毕 (如,main)
  • 虚拟机不用等待守护线程执行完毕 (如,后台记录操作日志,监控内存,垃圾回收……)
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
//上帝守护你
public class TestDaemon {

public static void main(String[] args) {
God god = new God();
You you = new You();

Thread thread = new Thread(god);
thread.setDaemon(true); //默认false表示是用户线程,正常的线程都是用户线程

thread.start(); //上帝守护线程启动

new Thread(you).start(); //你 用户线程启动
}
}

//上帝
class God implements Runnable{

@Override
public void run() {
while(true){
System.out.println("上帝保佑你");
}
}
}

//你
class You implements Runnable{

@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你一生都开心的活着");
}
System.out.println("=====GoodBye World!======");
}
}

8.线程同步机制

并发:同一个对象多个线程同时操作 (如:上万人同时抢票)

处理多线程问题时,多线程访问同一个对象(并发),并且某些线程还想修改这个对象。这时则需要线程同步。

线程同步其实是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面的线程使用完毕,下一个线程再使用。

线程同步的形成条件:队列+锁

同步方法和同步方法块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
◆由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法:synchronized方法和synchronized块

同步方法: public synchronized void method(int args) }

◆synchronized方法控制对“对象”的访问,每个对象对应一 把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。
缺陷:若将一个大的方法申明为synchronized将会影响效率

方法里需要修改的内容才需要锁,否则浪费资源

◆同步块: synchronized (Obj){}
◆Obj称之为同步监视器
◆Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
◆同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this , 就是这个对象本身,或者是class [反射中讲解]
◆同步监视器的执行过程
1.第一个线程访问,锁定同步监视器,执行其中代码.
2.第二个线程访问,发现同步监视器被锁定,无法访问.
3.第一个线程访问完毕,解锁同步监视器
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
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
//死锁:多个线程互相抱着对方需要的资源
public class DeadLock {

public static void main(String[] args) {
Makeup m1 = new Makeup(0,"小黑");
Makeup m2 = new Makeup(1,"小白");

m1.start();
m2.start();
}
}

//口红
class Lipstick{

}

//镜子
class Mirror{

}

//化妆
class Makeup extends Thread{

//需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();

int choice; //选择
String name; //使用化妆品的人

public Makeup(int choice, String name) {
this.choice = choice;
this.name = name;
}

@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException {
if(choice ==0){
synchronized (lipstick){ //获得口红的锁
System.out.println(this.name+"获得口红的锁");
Thread.sleep(1000);

synchronized (mirror){ //一秒钟后想获得镜子的锁
System.out.println(this.name+"获得镜子的锁");
}
}
}else{
synchronized (mirror){ //获得镜子的锁
System.out.println(this.name+"获得镜子的锁");
Thread.sleep(2000);
synchronized (lipstick) { //两秒钟后想获得口红的锁
System.out.println(this.name + "获得口红的锁");
}
}
}
}

}

解决办法:把同步代码块拿出来,不两个人同时抱一把锁。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 private  void makeup() throws InterruptedException {
if(choice ==0){
synchronized (lipstick){ //获得口红的锁
System.out.println(this.name+"获得口红的锁");
Thread.sleep(1000);
}
//从同步代码块拿出来
synchronized (mirror){ //一秒钟后想获得镜子的锁
System.out.println(this.name+"获得镜子的锁");
}
}else{
synchronized (mirror){ //获得镜子的锁
System.out.println(this.name+"获得镜子的锁");
Thread.sleep(2000);
}
//从同步代码块拿出来
synchronized (lipstick) { //两秒钟后想获得口红的锁
System.out.println(this.name + "获得口红的锁");
}
}
}

12345678910111213141516171819202122
2.死锁避免方法
  • 产生死锁的四个必要条件:
    • 互斥条件:一个资源每次只能被一个进程使用。
    • 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
    • 不剥夺条件:进程已获得的资源,在未使用完之前不能强行剥夺。
    • 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。

只要破坏其中一个。就可以避免死锁。

LOCK

◆从JDK 5.0开始,Java提供了更强大的线程同步机制_——过显式定义同步锁对象来实现同步。同步锁使用Lock对象充当;
◆java.util.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象
◆ReentrantLock类实现了Lock ,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显式加锁、释放锁。

线程协作 - 生产者消费者模式

线程通信
(1)应用场景:生产者和消费者问题

◆假设仓库中只能存放- -件产品,生产者将生产出来的产品放入仓库,消费者将仓库中产品取走消费.
◆如果仓库中没有产品,则生产者将产品放入仓库,否则停止生产并等待,直到仓库中的产品被消费者取走为止.
◆如果仓库中放有产品,则消费者可以将产品取走消费,否则停止消费并等待,直到仓库中再次放入产品为止.

(2)分析

这是一个线程同步问题,生产者和消费者共享同- -个资源,并且生产者和消费者之间相互依赖,互为条件.
◆对于生产者,没有生产产品之前,要通知消费者等待.而生产了产品之后又需要马上通知消费者消费
◆对于消费者,在消费之后,要通知生产者已经结束消费,需要生产新的产品以供消费.
◆在生产者消费者问题中,仅有synchronized是不够的
◆synchronized可阻止并发更新同一个共享资源,实现了同步
◆synchronized不能用来实现不同线程之间的消息传递(通信)

(3)解决方式

并发协作模型“生产者/消费者模式”–>

a.管程法

◆生产者:负责生产数据的模块(可能是方法,对象,线程,进程);
◆消费者:负责处理数据的模块(可能是方法,对象,线程,进程);
◆缓冲区:消费者不能直接使用生产者的数据,他们之间有个“缓冲区“
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据

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
//生产者
class Productor extends Thread{
SynContainer container;

public Productor(SynContainer container) {
this.container = container;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Chicken(i));
System.out.println("生产了第"+i+"只鸡");
}
}
}

//消费者
class Consumer extends Thread{
SynContainer container;

public Consumer(SynContainer container) {
this.container = container;
}

//消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了----第"+container.pop().id+"只鸡");
}
}

}

//产品
class Chicken{
int id; //产品编号
public Chicken(int id){
this.id = id;
}
}
1234567
//缓冲区
class SynContainer{
//需要一个容器大小
Chicken[] chickens = new Chicken[10];
//容器计数器
int count = 0;

//生产者放入产品
public synchronized void push(Chicken chicken){
//如果容器满了,就需要等待消费者消费
if(count == chickens.length){
//通知消费者消费,生产等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

//如果没有满,我们就需要丢入产品
chickens[count] = chicken;
count++;

//可以通知消费者消费了
this.notifyAll();
}


//消费者消费产品
public synchronized Chicken pop(){
//判断能否消费
if(count == 0){
//通等待生产者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

//如果可以消费。就取出产品
count--;
Chicken chicken = chickens[count];

//可以通知生产者消费了
this.notifyAll();

return chicken;
}
}

(代码不是很严谨,存在先消费后生产的问题)

b.信号灯法
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
//生产者--演员
class Player extends Thread{
TV tv;
public Player(TV tv) {
this.tv = tv;
}

@Override
public void run() {
for (int i = 0; i < 20; i++) {
if(i%2==0){
this.tv.play("快乐大本营");
}else{
this.tv.play("天天向上");
}
}
}
}

//消费者--观众
class Watcher extends Thread{
TV tv;
public Watcher(TV tv) {
this.tv = tv;
}

@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}
//产品--节目
class TV{
//演员表演,观众等待 T
//观众观看,演员等待 F
String voice; //表演节目
boolean flag = true;

//表演
public synchronized void play(String voice){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了:"+voice);
//通知观众观看
this.notifyAll(); //通知唤醒
this.voice = voice;
this.flag = !this.flag;
}

//观看
public synchronized void watch(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了:"+voice);
//通知演员表演
this.notifyAll();
this.flag = !this.flag;
}

}

线程池

使用线程池
◆背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
◆思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。
可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具。
◆好处:
提高响应速度(减少了创建新线程的时间)
降低资源消耗(重复利用线程池中线程,不需要每次都创建)
便于线程管理…
corePoolSize: 核心池的大小
maximumPoolSize:最大线程数
keepAliveTime: 线程没有任务时最多保持多长时间后会终止

◆JDK 5.0起提供了线程池相关API: ExecutorService 和Executors
◆ExecutorService: 真正的线程池接口。常见子类ThreadPoolExecutor
void execute(Runnable command) :执行任务/命令,没有返回值,一般用来执Runnable
Future submit(Callable task):执行任务,有返回值,一般用来执行Callable
void shutdown() :关闭连接池
◆Executors: 工具类、线程池的工厂类,用于创建并返回不同类型的线程池

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 TestPool {

public static void main(String[] args) {
//1.创建服务,创建线程池
ExecutorService service = Executors.newFixedThreadPool(10); //参数为线程池大小

//执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());

//2.关闭连接
service.shutdown();
}

}

class MyThread implements Runnable{

@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}