第九、十周总结
4.28
在b站尚硅谷学习
文章目录
一、 多线程
1.程序,进程,线程
每个线程独自拥有虚拟机栈和程序计数器
方法区和堆由多个线程共同使用 即一个进程 一个
2.单核与多核CPU,并行与并发
何时使用多线程?
1.程序需要同时执行两个或多个任务
2.程序需要实现一些需要等待的任务
3.需要一些后台运行的程序
3.创建多线程
(1)方式一:继承于Thread类
1.创建一个继承于Thread类的子类
2.重写Thread类的run()—>将此线程执行的操作声明在run()中
3.创建Thread类子类的对象
4.通过此对象调用start()
//1.创建一个继承于Thread类的子类
class MyThead extends Thread {
//2.重写Thread类的run()
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
}
public class ThreadTest{
public static void main(String[] args) {
//3.创建Thread类子类的对象
MyThead t1 = new MyThead();
//4.通过此对象调用start():①启动当前线程 ②调用当前线程的run()
t1.start();
//问题一:不能通过直接调用run()方法启动线程
// t1.run();//不是多线程,它仍在主线程中执行,只是单纯调用方法
//问题二:再启动一个线程,不可以让已经start()的线程去执行,会报IllegalThreadStateException错误
// t1.start();
//需要重新创建一个线程的对象让它start
MyThead t2 = new MyThead();
t2.start();
//如下方法输出仍在主线程中执行
for (int i = 0; i < 10; i++) {
if (i % 2 != 0) {
System.out.println(i+"------main------");
}
}
//----以上均为主线程做----//
//调用完start之后,t1开始独立执行,而此时主线程就自己继续了
}
}
.start()作用: ①启动当前线程 ②调用当前线程的run()
问题一:不能通过直接调用run()方法启动线程
不是多线程,它仍在主线程中执行,只是单纯调用方法
问题二:再启动一个线程,不可以让已经start()的线程去执行,会报IllegalThreadStateException错误
需要重新创建一个线程的对象让它start
例题:
public class Test {
public static void main(String[] args) {
MyThread1 m1 = new MyThread1();
MyThread2 m2 = new MyThread2();
m1.start();
m2.start();
//也可以创建Thread类的匿名子类的方式
// new Thread(){
// @Override
// public void run() {
// for (int i = 0; i < 100; i++) {
// if(i % 2 == 0){
// System.out.println(Thread.currentThread().getName() + ":" + i);
// }
// }
// }
// }.start();
// new Thread(){
// @Override
// public void run() {
// for (int i = 0; i < 100; i++) {
// if(i % 2 != 0){
// System.out.println(Thread.currentThread().getName() + ":" + i);
// }
// }
// }
// }.start();
}
}
class MyThread1 extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
class MyThread2 extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if(i % 2 != 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
结果:每次结果均不一样,体现了多线程
(2)创建多线程的方式二:实现Runnable接口
1.创建一个实现了Runnable接口的类
2. 实现类去实现Runnable中的抽象方法:run()
3. 创建实现类的对象
4. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
5. 通过Thread类的对象调用start()
//1. 创建一个实现了Runnable接口的类
class MThread implements Runnable{
//2. 实现类去实现Runnable中的抽象方法:run()
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
public class ThreadMethod2 {
public static void main(String[] args) {
//3. 创建实现类的对象
MThread mThread = new MThread();
//4. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
Thread t1 = new Thread(mThread);
t1.setName("线程1");
//5. 通过Thread类的对象调用start():① 启动线程 ②调用当前线程的run()-->调用了Runnable类型的target的run()
t1.start();
//再启动一个线程,遍历10以内的偶数
Thread t2 = new Thread(mThread);
t2.setName("线程2");
t2.start();
}
}
(3)创建线程的方式三:实现Callable接口。 — JDK 5.0新增
如何理解实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大?
- call()可以有返回值的。
- call()可以抛出异常,被外面的操作捕获,获取异常的信息
- Callable是支持泛型的
- Callable需要借助FutureTask类,比如获取返回结果
//1.创建一个实现Callable的实现类
class NumThread implements Callable{
//2.实现call方法,将此线程需要执行的操作声明在call()中
@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 1; i <= 100; i++) {
if(i % 2 == 0){
System.out.println(i);
sum += i;
}
}
return sum;
}
}
public class ThreadNew {
public static void main(String[] args) {
//3.创建Callable接口实现类的对象
NumThread numThread = new NumThread();
//4.将此Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
FutureTask futureTask = new FutureTask(numThread);
//5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()
new Thread(futureTask).start();
try {
//6.获取Callable中call方法的返回值
//get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值。
Object sum = futureTask.get();
System.out.println("总和为:" + sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
(4)创建线程的方式四:使用线程池
好处:
- 提高响应速度(减少了创建新线程的时间)
- 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
- 便于线程管理
corePoolSize:核心池的大小
maximumPoolSize:最大线程数
keepAliveTime:线程没有任务时最多保持多长时间后会终止
面试题:创建多线程有几种方式?四种!
class NumberThread implements Runnable{
@Override
public void run() {
for(int i = 0;i <= 100;i++){
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
}
class NumberThread1 implements Runnable{
@Override
public void run() {
for(int i = 0;i <= 100;i++){
if(i % 2 != 0){
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
}
public class ThreadPool {
public static void main(String[] args) {
//1. 提供指定线程数量的线程池
ExecutorService service = Executors.newFixedThreadPool(10);
ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;//强转成类才能调用属性、方法
//设置线程池的属性
// System.out.println(service.getClass());
// service1.setCorePoolSize(15);
// service1.setKeepAliveTime();
//2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
service.execute(new NumberThread());//适合适用于Runnable
service.execute(new NumberThread1());//适合适用于Runnable
// service.submit(Callable callable);//适合使用于Callable
//3.关闭连接池
service.shutdown();
}
}
4.测试Thread的常用方法
1.start():启动当前线程;调用当前线程的run();
2.run():通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中;
3.currentThread():静态方法,返回执行当前代码的线程;
4.getName():获取当前线程的名字;
//方式1
class ThreadMethodTest {
public static void main(String[] args) {
ThreadMethod h1 = new ThreadMethod();
h1.setName("线程1:");
h1.start();
//给主线程命名
Thread.currentThread().setName("主线程:");
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i);
}
}
}
}
//方式2
//在Theard子类中,与run()并列
public class ThreadMethod extends Thread {
. . . . . .
public ThreadMethod(String name){
super(name);
}
}
class ThreadMethodTest {
public static void main(String[] args) {
ThreadMethod h2 = new ThreadMethod("线程1:");
h2.start();
. . . . . .
}
}
}
}
5.setName():设置当前线程的名字
6.yield():释放当前cpu的执行权,一般会执行另一个线程,但也有拿回自己线程的可能
public class ThreadMethod extends Thread {
public void run() {
. . . . . .
if(i % 20 == 0){
yield();
}
}
}
7. join():在线程a中调用线程b的join(),此时线程a就进入阻塞状态,直到线程b完全执行完以后,线程a才结束阻塞状态。
class ThreadMethodTest {
public static void main(String[] args) {
ThreadMethod h2 = new ThreadMethod("线程1:");
h2.start();
//给主线程命名
Thread.currentThread().setName("主线程:");
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i);
}
if(i == 2){
try {
h2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
I1阶段:正常进行,直到满足i==2的条件开始执行jion(),即插入执行线程1; I2阶段:执行线程1,直至线程1执行结束;
l3阶段:紧接着执行除了线程1之外的线程。
8. stop():已过时。当执行此方法时,强制结束当前线程。
9. sleep(long millitime):让当前线程“睡眠”指定的millitime毫秒。在指定的millitime毫秒时间内,当前线程是阻塞状态。
sleep()方法有抛异常,而run()方法的父类没有抛异常,因此本类(子类)也不能将异常throws出去,又有重写的异常不能比父类大,因此需要用try-catch处理
public void run() {
. . . . . .
try {
sleep(1000);//延时1s出现下一个内容
} catch (InterruptedException e) {
e.printStackTrace();
}
}
10. isAlive():判断当前线程是否存活,即执行完就显示flase
System.out.println(h1.isAlive());
5.线程的调度
线程的优先级:
MAX_PRIORITY:10
MIN _PRIORITY:1
NORM_PRIORITY:5 -->默认优先级
如何获取和设置当前线程的优先级:
getPriority():获取线程的优先级
setPriority(int p):设置线程的优先级
说明:高优先级的线程要抢占低优先级线程cpu的执行权。但是只是从概率上讲,高优先级的线程高概率的情况下被执行。并不意味着只有当高优先级的线程执行完以后,低优先级的线程才执行。不能与sleep一起用,会有影响。
class HelloThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i);
}
}
}
public HelloThread(String name){
super(name);
}
}
public class ThreadMethodTest {
public static void main(String[] args) {
HelloThread h1 = new HelloThread("Thread:1");
//设置分线程的优先级
h1.setPriority(Thread.MAX_PRIORITY);
h1.start();
Thread.currentThread().setName("主线程");
//设置主线程的优先级
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
for (int i = 0; i < 100; i++) {
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i);
}
}
}
}
/**
* 例子:创建三个窗口卖票,总票数为100张.使用继承Thread类的方式
*
* 存在线程的安全问题,待解决。即出现三个窗口重复票号的情况。
*/
class Window extends Thread{
private static int ticket = 100;
@Override
public void run() {
while(true){
if(ticket > 0){
System.out.println(getName() + ":卖票,票号为:" + ticket);
ticket--;
}else{
break;
}
}
}
}
public class WindowTest {
public static void main(String[] args) {
Window t1 = new Window();
Window t2 = new Window();
Window t3 = new Window();
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
6.比较创建线程的两种方式
开发中:优先选择:实现Runnable接口的方式
原因:
1.实现的方式没有类的单继承性的局限性;
比如,该类自己有一个父类,但是在该创建方法下又必须extends Thread,由于单继承的原因,导致无法再继承其他的类了,造成麻烦。
2.实现的方式更适合来处理多个线程有共享数据的情况。
public class WindowTest1 {
public static void main(String[] args) {
Window1 w = new Window1();
//共享数据的体现
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
两者联系:public class Thread implements Runnable。
两者相同点:两种方式都需要重写run(),将线程要执行的逻辑声明在run()中。
7.线程的生命周期
8.线程安全问题
在Java中,我们通过同步机制,来解决线程的安全问题。
方式一:同步代码块
synchronized(同步监视器){
//需要被同步的代码
}
说明:
1.操作共享数据的代码,即为需要被同步的代码。 -->不能包含代码多了,也不能包含代码少了。
2.共享数据:多个线程共同操作的变量。比如:ticket就是共享数据。
3.同步监视器,俗称:锁。任何一个类的对象,都可以充当锁。
要求:多个线程必须要共用同一把锁。
补充:在实现Runnable接口创建多线程的方式中,我们可以考虑使用this充当同步监视器。
1.继承Thread类版
class Window2 extends Thread{
private static int ticket = 100;
private static Object obj = new Object();
@Override
public void run() {
while(true){
// synchronized (obj){//正确的
synchronized (Window2.class){//类也是对象Class clazz = Window2.class,Window2.class只会加载一次
//错误的方式:this代表着t1,t2,t3三个对象,对象不唯一则锁不唯一
// synchronized (this){
if(ticket > 0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + ":卖票,票号为:" + ticket);
ticket--;
}else{
break;
}
}
}
}
}
2.实现Runnable接口版
class Window1 implements Runnable{
private int ticket = 100;
// Dog dog = new Dog();
@Override
public void run() {
while(true){
synchronized (this){//此时的this:唯一的Window1的对象
// 方式二 :synchronized (dog) {
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket);
ticket--;
} else {
break;
}
}
}
}
}
共同:
class WindowTest1 {
public static void main(String[] args) {
//使用继承Thread类版
// Window2 t1 = new Window2();
// Window2 t2 = new Window2();
// Window2 t3 = new Window2();
//使用实现Runnable接口版
Window1 w = new Window1();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
方式二:同步方法。
如果操作共享数据的代码完整的声明在一个方法中,我们不妨将此方法声明同步的。
好处:同步的方式,解决了线程的安全问题。
局限性:操作同步代码时,只能有一个线程参与,其他线程等待。相当于是一个单线程的过程,效率低。
权限修饰符 synchronized 类型 方法名(){//默认同步监视器:this
}
关于同步方法的总结:
- 同步方法仍然涉及到同步监视器,只是不需要我们显式的声明。
- 非静态的同步方法,同步监视器是:this
静态的同步方法,同步监视器是:当前类本身
class Window3 implements Runnable {
private int ticket = 100;
@Override
public void run() {
while (true) {
show();
}
}
//同步方法
private synchronized void show(){//默认同步监视器:this
//synchronized (this){
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket);//Thread.currentThread():返回当前的线程对象;getName()属于Thread类
ticket--;
}
//}
}
}
class WindowTest3 {
public static void main(String[] args) {
Window3 w = new Window3();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
方式三:Lock锁 — JDK5.0新增
1. 面试题:synchronized 与 Lock的异同?
相同:二者都可以解决线程安全问题
不同:
synchronized机制在执行完相应的同步代码以后,自动的释放同步监视器;
Lock需要手动的启动同步(lock()),同时结束同步也需要手动的实现(unlock())
2.优先使用顺序:
Lock >>> 同步代码块(已经进入了方法体,分配了相应资源)>>> 同步方法(在方法体之外)
3.面试题:如何解决线程安全问题?有几种方式
class Window implements Runnable{
private int ticket = 100;
//1.实例化ReentrantLock
private ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while(true){
try{
//2.调用锁定方法lock()
lock.lock();
if(ticket > 0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":售票,票号为:" + ticket);
ticket--;
}else{
break;
}
}finally {
//3.调用解锁方法:unlock()
lock.unlock();
}
}
}
}
public class LockTest {
public static void main(String[] args) {
Window w = new Window();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
9.将单例模式中的懒汉式改写为线程安全的
class Bank{
private Bank(){
}
private static Bank instance = null;
public static Bank getInstance(){
//方式一:效率稍差,因每次都需要进去了才能判断
// synchronized (Bank.class) {
// if(instance == null){
//
// instance = new Bank();
// }
// return instance;
// }
//方式二:效率更高
if(instance == null){
synchronized (Bank.class) {
if(instance == null){
instance = new Bank();
}
}
}
return instance;
}
}