线程与进程
进程是执行程序的一次执行过程,是系统分配资源的单位。
一个进程中可以包含若干个线程,线程是CPU调度和执行的单位。
如果是模拟出来的多线程,同一个CPU在同一个时间只能执行一个代码,但因为切换地很快,所以让人看上去像是同时进行的。
(1)线程就是独立的执行路径
(2)在程序执行的时候,即使没有自己创建线程,后台也会有多个线程(主线程,gc线程)
(3)main是主线程,是系统的入口,用于执行整个程序
(4)在一个进程中,如果有多个线程,线程的运行由调度器安排调度,调度器与操作系统紧密相关,先后顺序不能人为干预
(5)对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制
(6)线程会带来额外的开销,如cpu调度时间,并发控制开销
(7)每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
多线程实现
1.继承Thread类
(1)自定义线程类继承Thread类
(2)重写run()方法,编写线程执行体
(3)创建线程对象,调用start()方法启动线程
线程start后,不一定立刻执行,CPU安排调度。
public class thread extends Thread{
@Override
public void run() {
for (int i=1;i<=10;i++){
System.out.println("I'm In MyThread.");
}
}
public static void main(String[] args) {
thread myThread=new thread();
myThread.start();
for (int i=1;i<=10;i++){
System.out.println("I'm In MainThread.");
}
}
}
下面是一个下载网图的样例程序:
首先,导入依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
然后自己写一个下载网图的类:
public class WebDownloader {
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
System.out.println(name);
} catch (IOException e) {
e.printStackTrace();
}
}
}
再写一个线程类:
public class thread extends Thread{
private String url;
private String name;
public thread(String url,String name){
this.url=url;
this.name=name;
}
@Override
public void run() {
WebDownloader webDownloader=new WebDownloader();
webDownloader.downloader(url,name);
}
public static void main(String[] args) {
thread t1=new thread("https://i0.hdslb.com/bfs/feed-admin/f6a2797b471448403692b19bda8242125062da59.jpg@336w_190h_1c.jpg","1.jpg");
thread t2=new thread("https://i0.hdslb.com/bfs/feed-admin/f6a2797b471448403692b19bda8242125062da59.jpg@336w_190h_1c.jpg","2.jpg");
thread t3=new thread("https://i0.hdslb.com/bfs/feed-admin/f6a2797b471448403692b19bda8242125062da59.jpg@336w_190h_1c.jpg","3.jpg");
t1.start();
t2.start();
t3.start();
}
}
即可下载网图,每次执行完后发现,下载顺序每次都是随机的。
2.实现Runnable接口
(1)定义MyRunnable类实现Runnable接口
(2)实现Run方法,编写线程执行体
(3)创建线程对象,调用start()方法启动线程
public class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("I'm in My Thread.");
}
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
new Thread(myRunnable).start();
for (int i = 1; i <= 10; i++) {
System.out.println("I'm in Main Thread.");
}
}
}
推荐使用这种方法,方便一个对象被多个线程使用。而由于java单继承具有局限性,不能很好适应oop,故不推荐第一种方法。
但是当一个对象被多个线程使用时,会发生并发问题。
下面是一个买票的一个样例。
public class MyRunnable implements Runnable {
private int ticketNum=10;
public void run() {
while (true){
if (ticketNum<=0) break;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->第"+ticketNum--+"张票");
}
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
new Thread(myRunnable,"A").start();
new Thread(myRunnable,"B").start();
new Thread(myRunnable,"C").start();
}
}
运行会发现,数据发生了紊乱,两个人有可能买了同一张票,甚至会出现购买到第0张票的情况。
3.实现Callable接口
(1)实现Callable接口,需要返回值类型
(2)重写call方法,需要抛出异常
(3)创建目标对象
(4)创建执行服务:ExecutorService ser=Executors.newFixedThreadPool(n);
(5)提交执行:Future<T> result1=ser.submit(t1);
(6)获取结果:T r1=result1.get();
(7)关闭服务:ser.shutdownNow();
public class MyCallable implements Callable<Boolean> {
public Boolean call() throws Exception {
for (int i=1;i<=100;i++){
System.out.println("I'm in thread "+thread.currentThread().getName());
}
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable1=new MyCallable();
MyCallable myCallable2=new MyCallable();
ExecutorService ser= Executors.newFixedThreadPool(2);
Future<Boolean> result1=ser.submit(myCallable1);
Future<Boolean> result2=ser.submit(myCallable2);
Boolean re1=result1.get();
Boolean re2=result2.get();
ser.shutdownNow();
System.out.println(re1);
System.out.println(re2);
}
}
线程状态
线程方法 | 说明 |
---|---|
setPriority(int newPriority) | 更改线程优先级 |
static void sleep(long millis) | 让当前正在执行的线程休眠 |
void join() | 等待该线程终止 |
static void yield() | 暂停当前的线程对象,执行其他线程 |
void interrupt() | 线程终止,已经废弃 |
boolean isAlive() | 判断线程是否处于活动状态 |
1. 停止线程
(1)不推荐使用JDK提供的stop,destroy方法,已经废弃
(2)推荐让线程自己停下来
(3)可以使用一个标志位作为终止变量
public class MyRunnable implements Runnable {
private boolean flag=true;
@Override
public void run() {
while (flag){
System.out.println("I'm in My Thread");
}
}
public void stop(){
flag=false;
}
}
标志位flag为true时,线程保持运行。
public class Test {
public static void main(String[] args) {
MyRunnable myRunnable=new MyRunnable();
new Thread(myRunnable).start();
for (int i = 0; i < 1000; i++) {
System.out.println("i'm in Main Thread");
if (i==900){
myRunnable.stop();
System.out.println("My Thread stop!!!");
}
}
}
}
2.线程休眠
(1)sleep(时间)指定当前线程阻塞的毫秒数
(2)sleep存在异常InterruptedException
(3)sleep时间到达后线程进入就绪状态
(4)sleep可以模拟网络延迟、倒计时等
(5)每一个对象都有一个锁,sleep不会释放锁
倒计时:
public class Test {
public static void main(String[] args) throws InterruptedException {
int time=10;
while (true){
System.out.println(time);
time--;
if (time<=0) break;
Thread.sleep(1000);
}
}
}
获取当前时间:
public class Test {
public static void main(String[] args) throws InterruptedException {
Date time=new Date(System.currentTimeMillis());
while (true){
System.out.println(new SimpleDateFormat("HH:mm:ss").format(time));
time=new Date(System.currentTimeMillis());
Thread.sleep(1000);
}
}
}
3.线程礼让
(1)礼让线程,让当前正在执行的线程暂停,但不阻塞
(2)将线程从运行状态转为就绪状态
(3)让cpu重新调度,礼让不一定成功
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" before");
Thread.yield();
System.out.println(Thread.currentThread().getName()+" after");
}
}
public class Test {
public static void main(String[] args) {
MyRunnable myRunnable=new MyRunnable();
new Thread(myRunnable,"a").start();
new Thread(myRunnable,"b").start();
}
}
4.线程join
(1)join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
(2)可以想象为插队
public class TestJoin implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("I'm in My Thread");
}
}
public static void main(String[] args) throws InterruptedException {
TestJoin testJoin=new TestJoin();
Thread thread=new Thread(testJoin);
thread.start();
for (int i = 0; i < 100; i++) {
System.out.println("I'm in Main Thread");
if (i==20) {
thread.join();
}
}
}
}
5.线程状态观测
线程状态 | 说明 |
---|---|
NEW | 尚未启动的线程 |
RUNNABLE | 在java虚拟机中执行的线程 |
BLOCKED | 被阻塞等待监视器锁定的线程 |
WAITING | 正在等待另一个线程执行特定动作的线程 |
TIMED_WAITING | 正在等待另一个线程执行动作达到指定等待时间的线程 |
TERMINATED | 已退出的线程 |
public class Test {
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("已经结束");
});
System.out.println(thread.getState());
thread.start();
System.out.println(thread.getState());
while (thread.getState()!=Thread.State.TERMINATED){
Thread.sleep(100);
System.out.println(thread.getState());
}
}
}
6.线程优先级
(1)Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行
(2)线程优先级用数字来表示,范围从1-10
(3)使用以下方式改变和获取优先级
getPriority()
setPriority(int n)
public class Test {
public static void main(String[] args) {
Runnable runnable=new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
};
//主线程
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
Thread t1=new Thread(runnable);
Thread t2=new Thread(runnable);
Thread t3=new Thread(runnable);
Thread t4=new Thread(runnable);
Thread t5=new Thread(runnable);
//先设置优先级再开始
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(8);
t4.start();
t5.setPriority(10);
t5.start();
}
}
具体调用还是由虚拟机决定,优先级只是起影响作用。
7.守护线程
(1)线程分为用户线程和守护线程
(2)虚拟机必须确保用户线程执行完毕
(3)虚拟机不必等待守护线程执行完毕
(4)如后台记录操作日志、监控内存、垃圾回收等
public class Test {
public static void main(String[] args) {
Runnable God=new Runnable() {
@Override
public void run() {
while (true){
System.out.println("God bless you.");
}
}
};
Runnable You=new Runnable() {
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("I'm very Happy.");
}
System.out.println("goodbye world!");
}
};
Thread godThread=new Thread(God);
godThread.setDaemon(true);
Thread youThread=new Thread(You);
godThread.start();
youThread.start();
}
}
线程同步
(1)线程同步机制
当多个线程操作同一个资源时,我们就需要线程同步。
并发:同一个对象被多个线程同时操作
处理多线程问题时,多个线程访问同一个对象,某些线程还想修改这个对象,这时候我们就需要线程同步。线程同步是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面的线程使用完毕,下一个线程再使用。
形成条件:队列+锁
由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可。存在以下问题:
(1)一个线程持有锁会导致其他所有需要此锁的线程挂起
(2)在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题
(3)如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题
线程不安全的list例子:
public class Test {
public static void main(String[] args){
List<String> list=new ArrayList<>();
for (int i=1;i<=10000;i++){
new Thread(()->list.add(Thread.currentThread().getName())).start();
}
System.out.println(list.size());
}
}
(2)同步方法
我们针对同步方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法:synchronized方法和synchronized块。
synchronized方法控制对对象的访问,每个对象对应一把锁,每个synchronized方法都必须取得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法被返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。若将一个大的方法申明为synchronized会影响效率。
方法中需要修改的地方才需要锁,锁的太多浪费资源。
买票的解决方案:
public class BuyTicket implements Runnable {
int ticketNum=10;
boolean flag=true;
@Override
public void run() {
while (flag){
buy();
}
}
synchronized void buy(){
if (ticketNum<=0) {flag=false;return;}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+ticketNum);
ticketNum--;
}
public static void main(String[] args) {
BuyTicket buyTicket=new BuyTicket();
new Thread(buyTicket,"我").start();
new Thread(buyTicket,"你").start();
new Thread(buyTicket,"她").start();
}
}
只要对于buy()方法加上synchronized修饰符就能解决了。由于这里只有一个对象一把锁,所以只要给方法加上修饰符就行了。
如果有多个对象想对同一个资源上同一把锁,则需要同步块。
同步块:synchronized(Obj){ … }
Obj被称为同步监视器,可以是任何对象,但是最好用共享资源作为同步监视器。同步方法中无需指定同步监视器,因为同步方法中的同步监视器就是this,即对象本身,或者是class。
同步监视器执行过程:
(1)第一个线程访问,锁定同步监视器,执行其中代码
(2)第二个线程访问,发现同步监视器被锁定,无法访问
(3)第一个线程访问完毕,解除同步监视器
(4)第二个线程访问,发现同步监视器没有锁,然后锁定并访问
list的正确做法:
public class Test {
public static void main(String[] args) throws InterruptedException {
List<String> list=new ArrayList<>();
for (int i=1;i<=10000;i++) {
new Thread(() -> {
synchronized (list) {
list.add(Thread.currentThread().getName());
}
}).start();
}
Thread.sleep(1000);
System.out.println(list.size());
}
}
对比:
//正确做法
public class Test {
public static void main(String[] args) throws InterruptedException {
List<String> list=new ArrayList<>();
Runnable runnable=new Runnable() {
@Override
public synchronized void run() {
list.add(Thread.currentThread().getName());
}
};
for (int i=1;i<=10000;i++) {
new Thread(runnable).start();
}
Thread.sleep(1000);
System.out.println(list.size());
}
}
//错误做法
public class Test {
public static void main(String[] args) throws InterruptedException {
List<String> list=new ArrayList<>();
for (int i=1;i<=10000;i++) {
new Thread(new Runnable() {
@Override
public synchronized void run() {
list.add(Thread.currentThread().getName());
}
}).start();
}
Thread.sleep(1000);
System.out.println(list.size());
}
}
两者区别在于,第一个只有一个runnable对象,只有一把锁,成功锁上了run方法。而第二个有10000个runnable,有10000把锁,这些锁互不干扰,因此无法锁上run方法,如果要修改,则要把list用同步块锁上。
ArrayList是多线程不安全的,如果要用线程安全的,需要使用CopyOnWriteArrayList。
(3)死锁
死锁是多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情况。某一个同步块同时拥有两个以上对象的锁时,可能发生死锁问题。
public class DeadLock extends Thread {
static String s1="资源1";
static String s2="资源2";
int choice;
String name;
public DeadLock(int choice, String name) {
this.choice = choice;
this.name = name;
}
@Override
public void run() {
if (choice==0){
synchronized (s1){
System.out.println(name+s1);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (s2){
System.out.println(name+s2);
}
}
}else {
synchronized (s2) {
System.out.println(name + s2);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (s1) {
System.out.println(name + s1);
}
}
}
}
public static void main(String[] args) {
DeadLock deadLock1=new DeadLock(0,"p1");
DeadLock deadLock2=new DeadLock(1,"p2");
deadLock1.start();
deadLock2.start();
}
}
产生死锁的四个必要条件:
(1)互斥条件:一个资源每次只能被一个进程使用
(2)请求与保持条件:一个进程因请求资源而阻塞时,对已经获得的资源保持不放
(3)不剥夺条件:进程已经获得的资源,在未使用完之前,不能强行剥夺
(4)循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
我们只要破坏四个条件中的任何一个,就不会发生死锁。
(4)Lock锁
(1)从JDK5开始,Java提供了更强大的线程同步机制——通过显式定义同步锁对象来实现同步。同步锁通过Lock对象充当。
(2)Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象。
(3)ReentrantLock实现了Lock接口,它拥有和synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显示加锁、释放锁。
public class MyRunnable implements Runnable {
private int ticketNum=10;
private ReentrantLock reentrantLock=new ReentrantLock();
public void run() {
while (true) {
try {
reentrantLock.lock();
if (ticketNum <= 0) break;
Thread.sleep(50);
System.out.println(Thread.currentThread().getName() + "-->第" + ticketNum-- + "张票");
}catch (Exception e) {
}finally {
reentrantLock.unlock();
}
}
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
new Thread(myRunnable,"A").start();
new Thread(myRunnable,"B").start();
new Thread(myRunnable,"C").start();
}
}
synchronized和lock的区别:
(1)Lock是显式锁(手动开启和关闭锁),synchronized是隐式锁,出了作用域自动释放
(2)Lock只有代码块锁,synchronized有代码块锁和方法锁
(3)使用Lock锁,JVM将花费较少的时间来调度线程,性能更好,并且具有较好的扩展性
(4)优先使用顺序:Lock>同步代码块>同步方法
线程通信
(1)生产者消费者模型
应用场景:生产者消费者问题
(1)假设仓库中只能存放一件产品,生产者将生产出来的产品放入仓库,消费者将仓库中产品取走消费
(2)如果仓库中没有产品,则生产者将产品放入仓库,否则停止生产并等待,直到仓库中的产品被消费者取走为止
(3)如果仓库中放有产品,则消费者可以将产品取走消费,否则停止消费并等待,直到仓库中再次放入产品为止
方法名 | 作用 |
---|---|
wait() | 表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁 |
wait(long timeout) | 指定等待的毫秒数 |
notify() | 唤醒一个处于等待状态的线程 |
notifyAll() | 唤醒同一个对象上所有调用wait()方法的线程,优先级高的优先调度 |
均是Object类的方法,都只能在同步方法或同步代码块中使用,否则会抛出异常IllegalMonitorStateException。
(2)管程法
生产者:负责生产数据的模块
消费者:负责处理数据的模块
缓冲区:消费者不能直接使用生产者的数据,他们之间有个缓冲区
缓冲区代码(重点):
public class Container {
String[] strings=new String[10]; //模拟产品
int count=0;
//方法一定要用同步修饰符,否则不能使用wait和notifyAll
public synchronized void push(String s) {
//缓冲区满,生产者暂停生产
//这里要用while循环判断,否则用if会导致错误
while (count==strings.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
strings[count]=s;
count++;
System.out.println(s+" pushed");
//通知消费者消费
this.notifyAll();
}
public synchronized String pop() {
//缓冲区空,消费者暂停消费
while (count==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
String result=strings[count];
System.out.println(result+" popped");
//通知生产者生产
this.notifyAll();
return result;
}
}
生产者:
public class Productor extends Thread{
Container container;
public Productor(Container container) {
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
container.push(i+"");
}
}
}
消费者:
public class Consumer extends Thread {
Container container;
public Consumer(Container container) {
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
container.pop();
}
}
}
测试代码:
public class Test {
public static void main(String[] args) {
//一个生产者,两个消费者
Container container=new Container();
new Productor(container).start();
new Consumer(container).start();
new Consumer(container).start();
}
}
(3)线程池
背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大
思路:提前创建好多个线程,放到线程池中,使用时直接获取,使用完放入池中。可以避免频繁创建销毁、实现重复利用。
好处:
(1)提高响应速度
(2)降低资源消耗
(3)便于线程管理
corePoolSize:核心池的大小
maximumPoolSize:最大线程数
keepAliveTime:线程没有任务时最多保持多长时间后会中止
JDK5.0起提供了线程池相关API:ExecutorService和Executors
ExecutorService:真正的线程池接口。常见子类:ThreadPoolExecutor
(1)void execute(Runnable command):执行任务,没有返回值
(2)Future<T> submit(Callable<T> task):执行任务,有返回值
(3)void shutdown():关闭线程池
Executors:工具类、线程池的工厂类,用于创建和返回不同类型的线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestThreadPool {
public static void main(String[] args) {
ExecutorService executorService= Executors.newFixedThreadPool(10);
Runnable runnable=new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
};
executorService.execute(runnable);
executorService.execute(runnable);
executorService.execute(runnable);
executorService.execute(runnable);
executorService.execute(runnable);
executorService.shutdown();
}
}