Day7 Java 多线程 2
uwupu 啦啦啦啦啦

线程协作

生产者消费者问题

这是一个线程同步问题,生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件。

Java线程通信

方法名 作用
wait() 表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁;
wait(long timeout) 指定等待的秒数
notify() 唤醒一个处于等待状态的线程
notifyAll() 唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调度

注:均是Object类的方法,都只能在同步方法或者同步代码块中使用,否则会抛出异常IllEgalMonitorStateException

问题解决

方式1

并发协作模型“生产者/消费者模式” -> 管程法

  • 生产者:负责生产数据的模块(可能是方法,对象,线程,进程);

  • 消费者:负责处理数据的模块(可能是方法,对象,线程,进程);

  • 缓冲区:消费者不能直接使用生产者的数据,他们之间有个“缓冲区”

生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据。

image

方式2

并发协作模型“生产者/消费者模式” -> 信号灯法

通过一个标志位解决问题。

线程池

背景:经常创建和销毁,使用了特别大的资源,比如并发情况下的线程,对性能影响很大。

思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁,实现重复利用。

优点:

  • 提高响应速度(减少了创建新线程的时间)
  • 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
  • 便于线程管理

使用线程池

JDK5.0起提供了线程池相关的API:ExecutorServiceExecutors

ExecutorService:线程池接口。子类有:ThreadPoolExecutor。

方法:

  • void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable。
  • <T>Future<T> submit(Callable<T> 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
26
27
public class Demo19_ThreadPool {
public static void main(String[] args) {
//创建线程池
//newFixedThreadPool参数为线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
//执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());

//关闭连接
service.shutdownNow();

}
}


class MyThread implements Runnable{

@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}

创建线程小结

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
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

//创建线程方式 3种
public class CreateThread {
public static void main(String[] args) {
new MyThread().start();//1

new Thread(new MyRunnable()).start();//2

//3
FutureTask<Integer> futureTask = new FutureTask<>(new MyCall());
new Thread(futureTask).start();
Integer rs=0;
try {
rs = futureTask.get();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(rs+" ");

}
}


//1. 继承Thread类
class MyThread extends Thread{
@Override
public void run() {
System.out.println("继承Thread");
}
}
//2. 实现Runnable接口
class MyRunnable implements Runnable {

@Override
public void run() {
System.out.println("实现Runnable接口");
}
}
//3. 实现Callable接口
class MyCall implements Callable<Integer>{

@Override
public Integer call(){
System.out.println("Call .");
return 123;
}
}
 评论