文章目录
多线程
1.进程、线程、多线程
- 一条线程指进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。
- 多任务指单个程序看起来同时完成多个任务,而多线程在更低一层扩展了多任务的概念。一个程序可以同时运行多个线程,则称之为多线程程序。
- 多进程指每个进程都拥有自己的一整套变量,而多线程只是共享数据(而这也会出现一些风险)。不过,线程更轻量级,创建一个线程比启动新进程的开销要小很多。
2.线程状态
一个线程的生命周期
线程可以有6种状态:调用getState()方法可得到线程当前状态
- New(新建):new Thread(str),此时线程还没有开始运行。
- Runnable(可运行):线程调用**start()**方法后就处于可运行状态(可能在运行也可能没有,要有操作系统提供具体的时间片)。
- Blocked(阻塞):线程试图获取一个内部对象锁失败时(因为锁被其他线程占用)
- Waiting(等待):当线程等待另一个线程通知调度器出现一个条件时。如调用Object.wait方法或Thread.join方法,或者是等待java.util.concurrent库中的Lock或Condition。
- Timed waiting(计时等待):有些方法有超时参数,调用这些方法时会进入计时等待状态(这一状态将一直保持到超时期满或接受到适当的通知)。如Thread.sleep、Object.wait、Thread.join、Lock.tryLock和Condition.await。
- Terminated(终止):run方法正常退出,线程自然终止;其他终止条件发生使线程意外终止。
3.创建多线程的方式
3.1 继承Thread类
public class TestThread extends Thread{
public TestThread(String name) {
super(name);
}
@Override
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println(getName() + "=" + i);
try {
Thread.sleep((int)(Math.random() * 100));
} catch (InterruptedException e) {}
}
System.out.println(getName() + "结束");
}
public static void main(String[] args) {
Thread t1 = new TestThread("线程1");
Thread t2 = new TestThread("线程2");
t1.start();
t2.start();
}
}
3.2 实现Runnable接口:(推荐使用) 避免单继承局限性,方便同一个对象被多个线程使用
public class RunnableDemo implements Runnable{
@Override
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "=" + i);
try {
//使当前线程睡眠一段时间
Thread.sleep((int)(Math.random() * 100));
} catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + "=" + "结束");
}
}
public static void main(String[] args) {
RunnableDemo task = new RunnableDemo();
Thread t1 = new Thread(task, "线程1");
Thread t2 = new Thread(task, "线程2");
t1.start();
t2.start();
//RunnableDemo task1 = new RunnableDemo("线程1");
//RunnableDemo task2 = new RunnableDemo("线程2");
//new Thread(task1).start();
//new Thread(task2).start();
}
}
3.3 Thread类
方法 | 描述 |
---|---|
void start() | 使该线程开始执行;Java 虚拟机调用该线程的 run 方法 |
void run() | 如果该线程是使用独立的 Runnable 运行对象构造的,则调用该 Runnable 对象的 run 方法;否则,该方法不执行任何操作并返回。 |
Thread.State getState() | 得到线程状态。NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED |
void join() | 等待指定的线程终止 |
void join(long millis) | 等待指定线程终止时间为millis毫秒 |
void setPriority(int priority) | 更改线程的优先级。优先级取值范围为1-10,MIN_PRIORITY(1), NORM_PRIORITY(5), MAX_PRIORITY(10) |
boolean isAlive() | 测试线程是否处于活动状态 |
void interrupt() | 向线程发送中断请求(线程的中断状态被设置为true)。如果当前线程被阻塞,则抛出InterruptedException |
void setDaemon(boolean on) | 将该线程标记为守护线程(为其它线程提供服务,如后台记录操作日志,监控内存,垃圾回收等)。线程分为用户线程和守护线程,虚拟机必须确保用户线程执行完毕,但不用等待守护线程执行完毕 |
静态方法
方法 | 描述 |
---|---|
void yield() | 暂停当前正在执行的线程对象,并执行其他线程 |
void sleep(long millis) | 在指定的毫秒数内让当前正在执行的线程休眠(暂停执行) |
boolean holdsLock(Object x) | 当且仅当当前线程在指定的对象上保持监视器锁时,才返回 true |
Thread currentThread() | 返回对当前正在执行的线程对象的引用 |
void dumpStack() | 将当前线程的堆栈跟踪打印至标准错误流 |
4.静态代理
package ThreadDemo;
//静态代理
//和thread底层实现一样
public class StaticProxy {
public static void main() {
new WeddingCompany(new You()).HappyMerry();
new Thread(()->System.out.println("线程")).start();
}
}
interface Merry {//声明一个接口
void HappyMerry();
}
class You implements Merry { //真实角色
@Override
public void HappyMerry() {
System.out.println("结婚");
}
}
class WeddingCompany implements Merry { //代理角色
private Merry target;
public WeddingCompany(Merry target) {
this.target = target;
}
@Override
public void HappyMerry() {
before();
this.target.HappyMerry();
after();
}
private void before() {
System.out.println("布置");
}
private void after() {
System.out.println("结束");
}
}
5.同步(Synchronized)
5.1 并发问题(竞态条件)
//多个线程同时操作同一个对象
//问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱,称之为竞态条件
public class TestBuyTickets implements Runnable{
private int tickets = 10;
private boolean flag = true;//外部停止方式
@Override
public void run() {
while(flag) {
if(tickets <= 0) {
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "拿到了第" + tickets-- + "张票");
}
}
public static void main(String[] args) {
TestBuyTickets tickets = new TestBuyTickets();
new Thread(tickets, "小明").start();
new Thread(tickets, "老师").start();
new Thread(tickets, "黄牛").start();
}
}
5.2 Synchronized关键字
要防止多个线程同时访问同一资源,就是防止多个线程同时执行共享对象的方法代码,这样的代码称为临界区。因此,给这个临界区加锁,其他线程在这个临界区被解锁之前无法执行其中的代码。Java的每个对象都可以有一个内在锁,也称作监视器锁,获得内在锁是独占该对象访问权的一种方式。Java通过同步代码块实现内在锁,支持两种同步:方法同步和块同步。
方法同步
public synchronized void method(...){}
当线程调用同步方法之前,自动尝试获得该对象(this)的内在锁(没获得则线程会阻塞),方法返回之前,该线程会一直占用该锁。并且占用锁的线程还可以调用同一个对象的其他同步方法。
缺陷:将一个大的方法声明为synchronized会影响效率。因为只读的代码不需要锁,只有修改的代码才需要。
块同步
synchronized(Obj){}
- Obj称为同步监视器
- Obj可以是任何对象,但推荐使用共享资源作为同步监视器
- 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是对象本身(this)或class(反射)
5.3 死锁
多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或多个线程同时等待对方释放资源,都停止执行的情形称为死锁。某一个同步块同时拥有两个以上对象的锁时,可能会发生死锁问题。
public class Test1 {
public static void main(String[] args) {
Makeup g1 = new Makeup(0,"g1");
Makeup g2 = new Makeup(1,"g2");
g1.start();
g2.start();
}
}
class Lipstick {
}
class Mirror {
}
class Makeup extends Thread {
//保证需要的资源只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;
String girlName;
Makeup(int choice,String girlName) {
this.choice = choice;
this.girlName = girlName;
}
@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.girlName+"获得口红的锁");
Thread.sleep(1000);
synchronized (mirror) {
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(1000);
}
}
// synchronized (mirror) { //解决方法,等一个锁释放后再请求另一个资源的的锁
// System.out.println(this.girlName+"获得镜子的锁");
// Thread.sleep(1000);
// }
} else {
synchronized (mirror) {
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(2000);
synchronized (lipstick) {
System.out.println(this.girlName+"获得口红的锁");
Thread.sleep(2000);
}
}
// synchronized (lipstick) {
// System.out.println(this.girlName+"获得口红的锁");
// Thread.sleep(2000);
// }
}
}
}
5.4 Lock
ublic class Test1 {
public static void main(String[] args) {
TestLock testLock = new TestLock();
new Thread(testLock).start();
new Thread(testLock).start();
new Thread(testLock).start();
}
}
class TestLock implements Runnable {
int tickets = 10;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();//重入锁,用来保护临界区
@Override
public void run() {
while(true) {
try {
lock.lock();//加锁
if (tickets > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(tickets--);
} else {
break;
}
} finally {
lock.unlock();//解锁
}
}
}
}
synchronized与lock的对比
6.线程协作(生产者/消费者模式)
解决线程之间通信的方法(java.lang.Object)
- void wait():使一个线程进入等待状态,直到得到其他线程通知。
- void wait(long millis):使一个线程进入等待状态,直到得到其他线程通知或经过了指定时间。
- void notify():唤醒一个处于等待状态的线程。
- void notifyAll():唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调度。
这些方法都只能再同步方法或同步代码块中调用。如果当前线程不是对象锁的拥有者会抛出IllegalMonitorStateException。
解决方式1——管程法
public class Test1 {
public static void main(String[] args) {
SynBuffer buffer = new SynBuffer();
new Producer(buffer).start();
new Consumer(buffer).start();
}
}
//生产者
class Producer extends Thread{
SynBuffer buffer;
public Producer(SynBuffer buffer) {
this.buffer = buffer;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
buffer.push(new Chicken(i));
System.out.println("生产了ID"+i+"鸡");
}
}
}
//消费者
class Consumer extends Thread{
SynBuffer buffer;
public Consumer(SynBuffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了ID"+buffer.pop().id+"鸡");
}
}
}
//产品
class Chicken{
int id;//产品编号
public Chicken(int id) {
this.id = id;
}
}
//缓冲区
class SynBuffer{
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;
}
}
解决方式2——信号灯法(标志位解决)
public class Test1 {
public static void main(String[] args) {
Movie movie = new Movie();
new Actor(movie).start();
new Audience(movie).start();
}
}
//生产者-—>演员
class Actor extends Thread {
Movie movie;
public Actor(Movie movie) {
this.movie = movie;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if(i%2 == 0) {
this.movie.play("节目1");
}else {
this.movie.play("节目2");
}
}
}
}
//消费者-->观众
class Audience extends Thread {
Movie movie;
public Audience(Movie movie) {
this.movie = movie;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
this.movie.watch();
}
}
}
//产品-->节目
class Movie {
//演员表演时观众等待
//观众观看时演员等待
String perform;//表演的节目
boolean flag = true;
//表演
public synchronized void play(String perform) {
if(!flag) {
try {
this.wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了"+perform);
//通知观众观看
this.notifyAll();
this.perform = perform;
this.flag = !this.flag;
}
//观看
public synchronized void watch() {
if(flag == true) {
try {
this.wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众观看了"+perform);
//通知演员
this.notifyAll();
this.flag = !this.flag;
}
}
7.线程池
7.1 Callable接口和Future
public class TestCallable implements Callable<Boolean>{
@Override
public Boolean call() {
System.out.println(Thread.currentThread().getName());
return true;
}
public static void main(String[] args) {
TestCallable task1 = new TestCallable();
TestCallable task2 = new TestCallable();
//创建执行服务,线程池
ExecutorService ser = Executors.newCachedThreadPool();
//提交执行
Future<Boolean> r1 = ser.submit(task1);
Future<Boolean> r2 = ser.submit(task2);
//获取结果
try {
boolean rs1 = r1.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
try {
boolean rs2 = r2.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
ser.shutdown();
}
}
7.2 Runnable接口
public class Test1 {
public static void main(String[] args) {
//创建线程池
ExecutorService ser = Executors.newFixedThreadPool(10);//线程池大小
//执行
ser.execute(new MyThread());
ser.execute(new MyThread());
ser.execute(new MyThread());
ser.shutdown();
}
}
class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName());
}
}
}