Java多线程
IntelliJ IDEA介绍
Eclipse->IBM IntelliJ IDEA->JetBrains
IDEA安装连接
IDEA和Eclipse的区别
IDEA中一个project相当于eclipse中的workspace。IDEA中的Module相当于Eclipse中的Module.在IDEA的工程中建立模块,模块中可以建立很多的包,包里面建立类。
一个项目由多个模块组成,模块之间并发运行。
IDEA主体字体修改视频教程
模板配置视频教程
基本概念:程序、进程、线程
程序:为了完成指定任务、用某种语言编写的一组指令的集合、
进程:程序的一次执行过程,正在运行的程序
线程:程序可以进一步细化为多个线程,是一个程序内部的一条执行路径。
并行:多个CPU同时执行多个任务
并发:一个CPU分多个时间片执行多个任务
单核CPU:一个计算引擎
多核CPU:一个CPU有多个计算引擎
线程的创建和使用 2种
第一种创建线程的方式
方法1:继承于Thread类
1.创建一个继承于Thread类的子类
2.重写Thread类的run(), 把创建线程需要做的事情写在run方法中
3.创建Thread类的子类对象
4.通过此类对象调用start()
package com.multithread.java;
/*
@author LiRui
@create 2021-10-26 16:52
*/
class MyThread extends Thread{//1.继承Thread类
//2.重写run方法
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread1");
}
}
}
class MyThread2 extends Thread{//1.继承Thread类
//2.重写run方法
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread2");
}
}
}
public class MultiThreadTest {
public static void main(String[] args) {
//3.创建子类对象
MyThread t1 = new MyThread();
MyThread2 t2 = new MyThread2();
//4.通过此类对象调用start()
t1.start();
t2.start();
}
}
问题1:不能直接调用run()的方式启动线程
问题2:再启动一个线程, 遍历100以内的偶数, 不可以让已经start()的线程去执行
多线程中常用的方法
1.start()启动当前线程;调用当前线程的run();
2.run(): 通常需要重写Thread类中的方法
3.currentThread()静态方法,返回执行当前代码的线程
4.getName():获取当前线程的名字
5.setName();设置当前线程的名字
6.yield() 释放当前CPU时间片
7.join()在线程a中调用线程b的join,此时线程a就进入阻塞状态,直到线程b‘完全执行以后,线程a才结束阻塞状态。
8.sleep(N)线程阻塞N ms
线程的调度
第二种线程创建方法
创建一个类实现Runnable接口,然后重写run()方法,再用该类的对象p去给Thread§构造函数, 调用start()方法
package com.multithread.java;/*
@author LiRui
@create 2021-10-27 10:01
*/
class MThread implements Runnable{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}
public class ThreadTest2 {
public static void main(String[] args) {
MThread p = new MThread();
new Thread(p).start();//匿名对象调用方法,参数传递为多态性
}
}
两种方式的对比
实现的方式要更好,继承在类的继承方面有局限性比如继承Thread类的类有父类需要继承,但是接口的实现可以完成多继承。对于共享的变量,继承的方式需要设置成静态的。
线程的生命周期
Thread类中定义了枚举类中包含六个类型来表示一个线程的不同状态。
NEW,RUNNABLE,BLOCKED,WATING,TIMED_WAITING,TERMINATED.
分别是,新建,就绪,运行,阻塞,死亡。
哪些操作会从一种状态到另一种状态
线程的同步 3种
主要解决线程的安全问题,主要是采用同步锁的方式。
方法1:同步代码块
synchronized(同步监视器){
//需要被同步的代码
}
说明:操作共享数据的代码,即为需要被同步的代码。共享数据:多个线程共享的数据。同步监视器:俗称,锁。任何一个类的对象都可以充当锁。要求:多个线程必须要共用同一把锁。
package com.multithread.java;/*
@author LiRui
@create 2021-10-27 10:01
*/
class MThread implements Runnable{
private int number=100;
Object obj =new Object();
@Override
public void run() {
synchronized (obj){
while (number>0){
System.out.println(Thread.currentThread().getName()+":"+number);
number--;
}
}
}
}
public class ThreadTest2 {
public static void main(String[] args) {
MThread p = new MThread();
Thread t1= new Thread(p);
Thread t2= new Thread(p);
Thread t3= new Thread(p);
t1.start();
t2.start();
t3.start();
}
}
方法2:同步方法
如果操作数据的代码正好声明在一个方法中,我们不妨将此方法声明为同步的。
package com.multithread.java;/*
@author LiRui
@create 2021-10-27 10:01
*/
class MThread implements Runnable{
private int number=100;
@Override
public void run() {
while (true){
show();
}
}
private synchronized void show(){//同步监视器是this
if (number>0){
System.out.println(Thread.currentThread().getName()+":"+number);
number--;
}
}
}
public class ThreadTest2 {
public static void main(String[] args) {
MThread p = new MThread();
Thread t1= new Thread(p);
Thread t2= new Thread(p);
Thread t3= new Thread(p);
t1.start();
t2.start();
t3.start();
}
}
线程死锁问题
方法3:锁 JDK5.0新加
package com.multithread.java;/*
@author LiRui
@create 2021-10-27 10:01
*/
import java.util.concurrent.locks.ReentrantLock;
class MThread implements Runnable{
private int number=100;
private ReentrantLock lock=new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock();
if (number>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":"+number);
number--;
}else{
break;
}
}finally {
lock.unlock();
}
}
}
}
public class ThreadTest2 {
public static void main(String[] args) {
MThread p = new MThread();
Thread t1= new Thread(p);
Thread t2= new Thread(p);
Thread t3= new Thread(p);
t1.start();
t2.start();
t3.start();
System.out.println("Finished");
}
}
线程的通信
采用wait()阻塞线程和notify()notifyAll()唤醒线程的方式来达到线程交替执行的目的
package com.multithread.java;/*
@author LiRui
@create 2021-10-27 10:01
*/
class MThread implements Runnable{
private int number=1;
@Override
public void run() {
synchronized (this){
while (true){
notify();
if(number<101){
System.out.println(Thread.currentThread().getName()+":"+number);
number++;
}else{
break;
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class ThreadTest2 {
public static void main(String[] args) {
MThread p = new MThread();
Thread t1= new Thread(p);
Thread t2= new Thread(p);
t1.start();
t2.start();
}
}
生产者消费者问题
两个线程都用来执行 同一个共享内存的操作来取出和放入变量。
package com.multithread.java;/*
@author LiRui
@create 2021-10-27 19:55
*/
class Foot{
private int foot=0;//食物为0
public synchronized void produceFoot(){
if(foot<20){
foot++;
System.out.println(Thread.currentThread().getName()+":开始生产第"+foot+"个食物");
notify();
}else{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void comsumeFoot(){
if(foot>0){
System.out.println(Thread.currentThread().getName()+":开始消费第"+foot+"个食物");
foot--;
notify();
}else{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Comsumer extends Thread{
private Foot f;
public Comsumer(Foot f){
this.f=f;
}
@Override
public void run() {
while (true){
f.comsumeFoot();
}
}
}
class Producer extends Thread{
private Foot f;
public Producer(Foot f){
this.f=f;
}
@Override
public void run() {
while (true){
f.produceFoot();
}
}
}
public class PCTest {
public static void main(String[] args) {
Foot f = new Foot();
Producer producer = new Producer(f);
Comsumer comsumer = new Comsumer(f);
producer.start();
comsumer.start();
}
}
JDK5.0新增的线程创建方式 2种
新增方式1:实现Callable接口
package com.multithread.java;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/*
@author LiRui
@create 2021-10-28 9:47
*/
class NumThread implements Callable {
@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 1; i < 101; i++) {
if (i%2==0){
System.out.println(i);
sum+=i;
}
}
return sum;
}
}
public class ThreadTestNew {
public static void main(String[] args){
NumThread numThread=new NumThread();
FutureTask fur=new FutureTask(numThread);
Thread t1=new Thread(fur);
t1.start();
try {
Object sum = fur.get();
System.out.println(sum);
}catch (InterruptedException e){
e.printStackTrace();
}catch (ExecutionException e){
e.printStackTrace();
}
}
}
新增方式2:使用线程池
package com.multithread.java;/*
@author LiRui
@create 2021-10-28 15:23
*/
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class NumberThread implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
class NumberThread1 implements Runnable{
@Override
public void run() {
for (int i = 10; i < 20; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
public class ThreadPool {
public static void main(String[] args) {
//提供指定线程数量的线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
//设置线程属性
//ThreadPoolExecutor service=(ThreadPoolExecutor)executorService;
//service.setCorePoolSize(15);
//service.setKeepAliveTime();
//执行指定线程的操作。需要实现Runnable或者Callable接口
executorService.execute(new NumberThread());//适用于Runnable
executorService.execute(new NumberThread1());//适用于Runnable
//executorService.submit();//适用于Callable
executorService.shutdown();
}
}
面试题:创建多线程有几种方式 4种
继承Thread类,实现Runnable接口, JDK 5.0 jdk 1.5.0 后:实现Callable接口,使用线程池