定义一个子类 Mythreads继承线程类ava.lang. Thread,重写run()方法
创建 Mythread类的对象
调用线程对象的 start()方法启动线程(启动后还是执行run方法的)
一定要把子线程放在主线程之前
package com.itheima.d1_create;
/**
目标:多线程的创建方式一:继承Thread类实现。
*/
public class ThreadDemo1 {
public static void main(String[] args) {
// 3、new一个新线程对象
Thread t = new MyThread();
// 4、调用start方法启动线程(执行的还是run方法)
t.start();
for (int i = 0; i < 5; i++) {
System.out.println("主线程执行输出:" + i);
}
}
}
/**
1、定义一个线程类继承Thread类
*/
class MyThread extends Thread{
/**
2、重写run方法,里面是定义线程以后要干啥
*/
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("子线程执行输出:" + i);
}
}
}
可以继续继承类和实现接口
package com.itheima.d1_create;
/**
目标:学会线程的创建方式二,理解它的优缺点。
*/
public class ThreadDemo2 {
public static void main(String[] args) {
// 3、创建一个任务对象
Runnable target = new MyRunnable();
// 4、把任务对象交给Thread处理
Thread t = new Thread(target);
// Thread t = new Thread(target, "1号");
// 5、启动线程
t.start();
for (int i = 0; i < 10; i++) {
System.out.println("主线程执行输出:" + i);
}
}
}
/**
1、定义一个线程任务类 实现Runnable接口
*/
class MyRunnable implements Runnable {
/**
2、重写run方法,定义线程的执行任务的
*/
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("子线程执行输出:" + i);
}
}
}
匿名内部类的改写
package com.itheima.d1_create;
/**
目标:学会线程的创建方式二(匿名内部类方式实现,语法形式)
*/
public class ThreadDemo2Other {
public static void main(String[] args) {
//此处为定义了匿名内部类,实现Runnable接口
Runnable target = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("子线程1执行输出:" + i);
}
}
};
//把任务对象交给Thread处理
Thread t = new Thread(target);
//启动线程
t.start();
Runnable target1 = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("子线程4执行输出:" + i);
}
}
};
//把任务对象交给Thread处理
Thread t1 = new Thread(target1);
//启动线程
t1.start();
Runnable target2 = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("子线程5执行输出:" + i);
}
}
};
//把任务对象交给Thread处理
Thread t2 = new Thread(target2);
//启动线程
t2.start();
//此处改写: 将匿名类作为参数传递进函数
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("子线程2执行输出:" + i);
}
}
}).start();
//进一步简化
new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println("子线程3执行输出:" + i);
}
}).start();
for (int i = 0; i < 10; i++) {
System.out.println("主线程执行输出:" + i);
}
}
}
前两种不能直接返回结果
1)call对象不是线程对象 所以需要交给Thread
2)但又不能直接交给Thread,所以需要用FutureTask封装
3)FutureTask对象的作用1: 是Runnable的对象(实现了Runnable接口),可以交给Thread了
4)FutureTask对象的作用2: 可以在线程执行完毕之后通过调用其get方法得到线程执行完成的结果
package com.itheima.d1_create;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
目标:学会线程的创建方式三:实现Callable接口,结合FutureTask完成。
*/
public class ThreadDemo3 {
public static void main(String[] args) {
// 3、创建Callable任务对象
Callable<String> call = new MyCallable(100);
// 4、把Callable任务对象 交给 FutureTask 对象
// FutureTask对象的作用1: 是Runnable的对象(实现了Runnable接口),可以交给Thread了
// FutureTask对象的作用2: 可以在线程执行完毕之后通过调用其get方法得到线程执行完成的结果
FutureTask<String> f1 = new FutureTask<>(call);
// 5、交给线程处理
Thread t1 = new Thread(f1);
// 6、启动线程
t1.start();
Callable<String> call2 = new MyCallable(200);
FutureTask<String> f2 = new FutureTask<>(call2);
Thread t2 = new Thread(f2);
t2.start();
//此处因为重写call方法时有错误情况
// @Override
// public String call() throws Exception {
// int sum = 0;
// for (int i = 1; i <= n ; i++) {
// sum += i;
// }
// return "子线程执行的结果是:" + sum;
// }
try {
// 如果f1任务没有执行完毕,这里的代码会等待,直到线程1跑完才提取结果。
String rs1 = f1.get();
System.out.println("第一个结果:" + rs1);
} catch (Exception e) {
e.printStackTrace();
}
try {
// 如果f2任务没有执行完毕,这里的代码会等待,直到线程2跑完才提取结果。
String rs2 = f2.get();
System.out.println("第二个结果:" + rs2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
1、定义一个任务类 实现Callable接口 应该申明线程任务执行完毕后的结果的数据类型
*/
class MyCallable implements Callable<String>{
private int n;
public MyCallable(int n) {
this.n = n;
}
/**
2、重写call方法(任务方法)
*/
@Override
public String call() throws Exception {
int sum = 0;
for (int i = 1; i <= n ; i++) {
sum += i;
}
return "子线程执行的结果是:" + sum;
}
}
线程类本身的API
1)setName为多线程取名字去与其他线程进行区分
2)currentThread哪个线程执行他,他就得到哪个线程对象(从而获得主线程对象)
package com.itheima.d2_api;
/**
目标:线程的API
*/
public class ThreadDemo01 {
// main方法是由主线程负责调度的
public static void main(String[] args) {
Thread t1 = new MyThread("1号");
// t1.setName("1号");
t1.start();
System.out.println(t1.getName());
Thread t2 = new MyThread("2号");
// t2.setName("2号");
t2.start();
System.out.println(t2.getName());
// 哪个线程执行它,它就得到哪个线程对象(当前线程对象)
// 主线程的名称就叫main
Thread m = Thread.currentThread();
System.out.println(m.getName());
m.setName("最牛的线程");
for (int i = 0; i < 5; i++) {
System.out.println( m.getName() + "输出:" + i);
}
}
}
package com.itheima.d2_api;
public class MyThread extends Thread{
public MyThread() {
}
public MyThread(String name) {
// 为当前线程对象设置名称,送给父类的有参数构造器初始化名称
super(name);
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println( Thread.currentThread().getName() + "输出:" + i);
}
}
}
package com.itheima.d2_api;
/**
目标:线程的API 休眠
*/
public class ThreadDemo02 {
// main方法是由主线程负责调度的
public static void main(String[] args) throws Exception {
for (int i = 1; i <= 5; i++) {
System.out.println("输出:" + i);
if(i == 3){
// 让当前线程进入休眠状态
// 段子:项目经理让我加上这行代码,如果用户愿意交钱,我就注释掉。
Thread.sleep(3000);
}
}
}
}
线程安全问题——解决方法、线程同步
线程同步(上锁)有三种方式
同步代码块(锁代码)
public void drawMoney(double money) {
// 1、拿到是谁来取钱
String name = Thread.currentThread().getName();
// 同步代码块
// 小明 小红
// this == acc 共享账户
// 即所要锁的对象应该是两人共享的那个账户!//这个this很重要
synchronized (this) {
// 2、判断余额是否足够
if(this.money >= money){
// 钱够了
System.out.println(name+"来取钱,吐出:" + money);
// 更新余额
this.money -= money;
System.out.println(name+"取钱后,余额剩余:" + this.money);
}else{
// 3、余额不足
System.out.println(name+"来取钱,余额不足!");
}
}
}
同步方法(锁方法)-同步代码块锁的范围更小,同步方法锁的范围更大
public synchronized void drawMoney(double money) {
// 1、拿到是谁来取钱
String name = Thread.currentThread().getName();
// 2、判断余额是否足够
if(this.money >= money){
// 钱够了
System.out.println(name+"来取钱,吐出:" + money);
// 更新余额
this.money -= money;
System.out.println(name+"取钱后,余额剩余:" + this.money);
}else{
// 3、余额不足
System.out.println(name+"来取钱,余额不足!");
}
}
Lock锁(接口不能创建对象)
package com.itheima.d6_thread_synchronized_lock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
账户类:余额 , 卡号。
*/
public class Account {
private String cardId;
private double money; // 余额 关键信息
// final修饰后:锁对象是唯一和不可替换的,非常专业
private final Lock lock = new ReentrantLock();
public Account() {
}
public Account(String cardId, double money) {
this.cardId = cardId;
this.money = money;
}
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
/**
小明 小红
*/
public void drawMoney(double money) {
// 1、拿到是谁来取钱
String name = Thread.currentThread().getName();
// 2、判断余额是否足够
// 小明 小红
lock.lock(); // 上锁
try {
if(this.money >= money){
// 钱够了
System.out.println(name+"来取钱,吐出:" + money);
// 更新余额
this.money -= money;
System.out.println(name+"取钱后,余额剩余:" + this.money);
}else{
// 3、余额不足
System.out.println(name+"来取钱,余额不足!");
}
} finally {
lock.unlock(); // 解锁
//这样能够不依赖于面向对象的设计
}
}
}
线程通信
生产者与消费者模型
CallSystem.class.notify();//唤醒另一个在等待的线程
CallSystem.class.wait(); // 让当前线程等待并释放所占锁
//顺序固定
package com.itheima.d7_thread_comunication;
/**
呼叫系统。
*/
public class CallSystem {
// 定义一个变量记录当前呼入进来的电话。
public static int number = 0; // 最多只接听一个。
/* 接入电话
*/
public synchronized static void call() {
try {
number++;
System.out.println("成功接入一个用户,等待分发~~~~");
// 唤醒别人 : 1个
CallSystem.class.notify();
// 让当前线程对象进入等待状态。
CallSystem.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
分发电话
*/
public synchronized static void receive() {
try {
String name = Thread.currentThread().getName();
if(number == 1){
System.out.println(name + "此电话已经分发给客服并接听完毕了~~~~~");
number--;
// 唤醒别人 : 1个
CallSystem.class.notify();
CallSystem.class.wait(); // 让当前线程等待
}else {
// 唤醒别人 : 1个
CallSystem.class.notify();
CallSystem.class.wait(); // 让当前线程等待
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
线程池(复用线程的技术)(重要)
固定三个工作线程来排队解决任务队列从而减少资源利用压力
线程池实现常用API,参数说明
package com.itheima.d8_threadpool;
public class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + "输出了:HelloWorld ==> " + i);
}
try {
System.out.println(Thread.currentThread().getName() + "本任务与线程绑定了,线程进入休眠了~~~");
Thread.sleep(10000000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.itheima.d8_threadpool;
import java.util.concurrent.*;
/**
目标:自定义一个线程池对象,并测试其特性。
*/
public class ThreadPoolDemo1 {
public static void main(String[] args) {
// 1、创建线程池对象
/**
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
*/
ExecutorService pool = new ThreadPoolExecutor(3, 5 ,
6, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5) , Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy() );
// 2、给任务线程池处理。
Runnable target = new MyRunnable();
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
// 创建临时线程
pool.execute(target);
pool.execute(target);
// // 不创建,拒绝策略被触发!!!
// pool.execute(target);
// 关闭线程池(开发中一般不会使用)。
// pool.shutdownNow(); // 立即关闭,即使任务没有完成,会丢失任务的!
pool.shutdown(); // 会等待全部任务执行完毕之后再关闭(建议使用的)
}
}
package com.itheima.d8_threadpool;
import java.util.concurrent.Callable;
/**
1、定义一个任务类 实现Callable接口 应该申明线程任务执行完毕后的结果的数据类型
*/
public class MyCallable implements Callable<String>{
private int n;
public MyCallable(int n) {
this.n = n;
}
/**
2、重写call方法(任务方法)
*/
@Override
public String call() throws Exception {
int sum = 0;
for (int i = 1; i <= n ; i++) {
sum += i;
}
return Thread.currentThread().getName()
+ "执行 1-" + n+ "的和,结果是:" + sum;
}
}
package com.itheima.d8_threadpool;
import java.util.concurrent.*;
/**
目标:自定义一个线程池对象,并测试其特性。
*/
public class ThreadPoolDemo2 {
public static void main(String[] args) throws Exception {
// 1、创建线程池对象
/**
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
*/
ExecutorService pool = new ThreadPoolExecutor(3, 5 ,
6, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5) , Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy() );
// 2、给任务线程池处理。
Future<String> f1 = pool.submit(new MyCallable(100));
Future<String> f2 = pool.submit(new MyCallable(200));
Future<String> f3 = pool.submit(new MyCallable(300));
Future<String> f4 = pool.submit(new MyCallable(400));
Future<String> f5 = pool.submit(new MyCallable(500));
// String rs = f1.get();
// System.out.println(rs);
System.out.println(f1.get());
System.out.println(f2.get());
System.out.println(f3.get());
System.out.println(f4.get());
System.out.println(f5.get());
}
}
目标:使用Executors的工具方法直接得到一个线程池对象。
package com.itheima.d8_threadpool;
import java.util.concurrent.*;
/**
目标:使用Executors的工具方法直接得到一个线程池对象。
*/
public class ThreadPoolDemo3 {
public static void main(String[] args) throws Exception {
// 1、创建固定线程数据的线程池
ExecutorService pool = Executors.newFixedThreadPool(3);
pool.execute(new MyRunnable());
pool.execute(new MyRunnable());
pool.execute(new MyRunnable());
pool.execute(new MyRunnable()); // 已经没有多余线程了
}
}
定时器(任务延时调用,任务周期调用)
package com.itheima.d9_timer;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
目标:Timer定时器的使用和了解。
Timer是单线程,处理多个任务按照顺序执行,存在延时与设置定时器的时间有出入
可能因为其中的某个任务的异常使Timer线程死掉,从而影响后续任务执行
*/
public class TimerDemo1 {
public static void main(String[] args) {
// 1、创建Timer定时器
Timer timer = new Timer(); // 定时器本身就是一个单线程。
// 2、调用方法,处理定时任务
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "执行AAA~~~" + new Date());
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}, 0, 2000);
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "执行BB~~~"+ new Date());
System.out.println(10/0);
}
}, 0, 2000);
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "执行CCC~~~"+ new Date());
}
}, 0, 3000);
}
}
主流定时器——内部是线程池
package com.itheima.d9_timer;
import sun.java2d.d3d.D3DScreenUpdateManager;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
目标:Timer定时器的使用和了解。
基于线程池,某个任务的执行情况不会影响其他定时任务的执行
*/
public class TimerDemo2 {
public static void main(String[] args) {
// 1、创建ScheduledExecutorService线程池,做定时器
ScheduledExecutorService pool = Executors.newScheduledThreadPool(3);
// 2、开启定时任务
pool.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() +
"执行输出:AAA ==》 " + new Date());
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 0, 2, TimeUnit.SECONDS);
pool.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "执行输出:BBB ==》 " + new Date());
System.out.println(10 / 0);
}
}, 0, 2, TimeUnit.SECONDS);
pool.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "执行输出:CCC ==》 " + new Date());
}
}, 0, 2, TimeUnit.SECONDS);
pool.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//在这里写要干的活
}
},0,2,TimeUnit.SECONDS);
}
}
补充知识:线程的并发并行、生命周期
并发:由于打的足够快,导致感觉在同时打八个学生
并行:八核八个CPU导致同时可以打八个学生
并发并行同时即:一下打八个,又打的足够快,
生命周期
NEW:新建状态
RUNNABLE:可运行状态
BLOCKED:阻塞状态(阻塞锁)
WAITING:无线程状态,等待别人唤醒
TIMED_WAITING:休眠状态(计时等待)
TERMINATED:死亡状态