多线程Thread类
1.多线程概述
1.基本概念
程序(program)是为完成特定任务、用某种语言编写的一组指令的集合。即指一段静态的代码,静态对象。
进程(process)是程序的一次执行过程,或是正在运行的一个程序。是一个动态的过程:有它自身的产生、存在和消亡的过程–生命周期
进程是资源分配的单位,系统在运行时会为每个进程分配不同的内存区域
线程(thread)进程可进一步细化为线程,是一个程序内部的一条执行路径
若一个程序同一时间并行执行多个线程,就是支持多线程的
线程作为调度和执行的单位,每一个线程拥有独立的运行栈和程序计数器(pc)。线程切换的开销小
一个进程中的多个线程共享相同的内存单元/内存地址空间–他们从同一堆中分配对象,可以访问相同的变量和对象,这就使得线程间通信更简便、高效,但多个线程操作共享的系统资源可能就会带来安全隐患
小结:进程可以细化为多线程
每个线程,拥有自己独立的:栈,程序计数器
多个线程,共享同一个进程中的结构:方法区,栈
2.单核CPU和多核CPU的理解
3.使用多线程的优点
背景:单核CPU为例,只使用单个线程先后完成多个任务(调用多个方法),肯定比用多个线程来完成用的时间更短,为何需要多线程?
多线程程序的优点:
①.提高应用程序的响应,对图形化界面更有意义,增强用户体验
②.提高计算机系统CPU的利用率
③.改善程序结构,将既长又复杂的进程分为多个线程,独立运行,利于理解和修改
4.何时需要多线程?
①.程序需要同时执行两个或多个任务
②.程序需要实现一些需要等待的任务时,如客户输入,文件读写操作,网络操作,搜索等
③.需要一些后台运行程序时
5.线程的创建和启动
Java语言的JVM允许程序运行多个线程,它通过java.lang.Thread类体现
Thread类的特性
每个线程都是通过某个特定Thread对象的run()犯法来完成操作的,经常把run()方法的主体称为线程体
通过该Thread对象的start()方法来起动这个线程,而非直接调用run()
6.线程的调度
抢占式:高优先级抢占低优先级
Java调度方法
通优先级线程先进先出,使用时间片策略
对高优先级,使用优先调度的抢占式策略
7.线程的优先等级
8.生命周期
2.多线程的常用方法
1.start():启动当前线程,调用当前线程的run()
2.run():通常需要重写Thread类中的方法,创建的线程要执行的操作声明在此方法中
3.currentThread():静态方法,返回当前代码执行的线程
4.getName():获取当前线程的名字
5.setName():设置当前线程的名字
6.yield():释放CPU的执行权
7.join():在线程a中调用线程b的join()方法,此时线程a就进入阻塞状态,直到
线程b完全执行以后,线程a才结束阻塞状态
8.stop():已过时,当执行此方法时,强制结束当前线程
9.sleep(long millitime):让当前线程"睡眠"指定的millitime毫秒,在指定的毫秒时间内
当前的线程是阻塞状态
10.isAlive():判断当前线程是否存活
11.getPriority():获取线程的优先级
12.setPriority():设置线程的优先级
13.wait():一旦执行此方法,当前线程就会进入阻塞状态,并释放同步监视器
14.notify():一旦执行,就会唤醒被wait()的一个线程,如果有多个线程,唤醒优先级高的线程
15.notifyAll():一旦执行,唤醒所有的wait()的线程
public class ThreadMethodTest2{
public static void main(String[] args) {
MyThread mt1 = new MyThread("thread:1 ");
// mt1.setName("线程1");
mt1.setPriority(Thread.MAX_PRIORITY);
mt1.start();
//给主线程命名
Thread.currentThread().setName("主线程");
for (int i = 0; i < 100; i++) {
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + Thread.currentThread().getPriority() + " " + i);
}
if(i == 20){
try {
mt1.join();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
System.out.println(mt1.isAlive());
}
}
class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if(i % 2 == 0){
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + Thread.currentThread().getPriority() + " " + i);
}
// if(i % 20 == 0){
// yield();
// }
}
}
public MyThread(String name){
super(name);
}
}
/* 涉及到三个方法:
* wait():一旦执行此方法,当前线程就会进入阻塞状态,并释放同步监视器
* notify():一旦执行,就会唤醒被wait()的一个线程,如果有多个线程,唤醒优先级高的线程
* notifyAll():一旦执行,唤醒所有的wait()的线程
*
* 说明:
* 1.wait(),notify(),notifyAll()三个方法必须使用在同步代码块或同步方法中
* 2.wait(),notify(),notifyAll()三个方法调用者必须是同步代码块或同步方法中的同步监视器
* 否则,会出现IllegalMonitorStateException
* 3.wait(),notify(),notifyAll()三个方法时定义在java.lang.Object类中
*
* 面试题:sleep()wait()的异同?
* 1.相同点:一旦执行方法,都可以使得当前的线程进入阻塞状态
* 2.不同点:1.声明位置不同:Thread类中声明sleep(),object类中声明wait()
* 2.调用的范围不同:sleep()可以在任何需要的场景下调用,wait()必须使用在同步代码块中或同步方法中
* 3.关于是否释放同步监视器:如果两个方法都使用在同步代码块或同步方法中,sleep()不会释放锁,wait()会释放锁
*
*/
public class CommunicationTest {
public static void main(String[] args) {
Number number = new Number();
Thread t1 = new Thread(number);
Thread t2 = new Thread(number);
t1.setName("线程1");
t2.setName("线程2");
t1.start();
t2.start();
}
}
class Number implements Runnable{
private int number = 1;
@Override
public void run() {
while (true){
synchronized (this){
notify();
if (number <= 100){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + number);
number++;
try {
//使得调用wait()方法的线程进行阻塞状态,会释放锁
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
break;
}
}
}
}
}
3.多线程的实现方式
1.继承Thread类
多线程的创建:方式一:继承于Thread类
1.创建一个继承与Thread类的子类
2.重写Thread类的run()方法
3.创建Thread类的子类对象
4.通过此对象调用start()
//1.创建一个继承与Thread类的子类
class MultithreadingTest extends Thread{
//2.重写Thread类的run()方法
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
}
}
class ThreadTest{
public static void main(String[] args) {
//3.创建Thread类的子类对象
MultithreadingTest threadTest = new MultithreadingTest();
//4.通过此对象调用start():①启动当前线程②调用当前线程的run()
threadTest.start();
//问题一:我们不能直接通过调用run()方法启动线程
//threadTest.run();
//问题二:在启动一个线程遍历
//不可以通过再次调用start()增加一个线程,异常java.lang.IllegalThreadStateException
//threadTest.start();
MultithreadingTest threadTest1 = new MultithreadingTest();
threadTest1.start();
//如下操作仍然是在main线程中执行
for (int i = 0; i < 100; i++) {
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + " " + i + "**********");
}
}
}
}
public class ThreadTest1 {
public static void main(String[] args) {
// MyThread1 mt1 = new MyThread1();
// MyThread2 mt2 = new MyThread2();
//
// mt1.start();
// mt2.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 < 100; 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 < 100; i++) {
if(i % 2 != 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
2.实现Runnable接口
创建多线程的方式二:实现Runnable接口
1.创建一个实现了Runnable接口的类
2.实现类去实现Runnable中的抽象方法,run()
3.创建实现类的对象
4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
5.通过Thread类的对象调用start()
比较创建线程的两种方式:
开发中,优先使用实现Runnable接口的方式
原因:1.实现的方式没有类的单继承的局限性
2.实现的方式更适合来处理多个线程有共享数据的情况
联系:Thread类也是实现了Runnable接口
相同点:两种方式都需要重写run(),将线程要执行的逻辑声明在run()中
//1.创建一个实现了Runnable接口的类
class MyThread3 implements Runnable{
//2.实现类去实现Runnable中的抽象方法,run()
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName()+ " " + i);
}
}
}
}
public class ThreadTest4 {
public static void main(String[] args) {
//3.创建实现类的对象
MyThread3 mt3 = new MyThread3();
//4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
Thread t3 = new Thread(mt3);
//5.通过Thread类的对象调用start()①启动线程②调用当前线程的run()--调用了rannable类型的target的run()
t3.start();
Thread t4 = new Thread(mt3);
t4.start();
}
}
class Window3 implements Runnable{
private int ticket = 100;
@Override
public void run() {
while (true){
if(ticket > 0){
System.out.println(Thread.currentThread().getName() + " 票号:" + ticket);
ticket--;
}else {
break;
}
}
}
}
public class ThreadTest5 {
public static void main(String[] args) {
Window3 w3 = new Window3();
Thread t1 = new Thread(w3);
Thread t2 = new Thread(w3);
Thread t3 = new Thread(w3);
//一个线程放进三个对象中 ticket不要static
t1.start();
t2.start();
t3.start();
}
}
3.实现Callable接口
和Runnable接口相比
1.有返回值
2.可以抛出异常
3.支持泛型返回值
4.需要借助FutureTask类
创建多线程的方式三:实现Callable接口
1.创建一个Callable的实现类
2.实现call()方法,将此线程需要执行的操作声明在call方法中,可以有返回值
3.创建一个Callable接口的实现类对象
4.创建一个FutureTask对象并将实现类对象传入
5.FutureTask对象作为参数传入Thread类的构造器中,创建Thread()对象,调用start()
6.获取Callable中的方法的返回值
如何理解实现Callable接口方式创建多线程比实现Runnable接口创建多线程方式强大?
1.call()可以有返回值
2.call()可以抛出异常
3.Callable是支持泛型的
public class CallableTest1 {
public static void main(String[] args) {
//3.创建一个Callable接口的实现类对象
NumThread numThread = new NumThread();
//4.创建一个FutureTask对象并将实现类对象传入
FutureTask<Integer> futureTask = new FutureTask<>(numThread);
//5.FutureTask对象作为参数传入Thread类的构造器中,创建Thread()对象,调用start()
Thread thread = new Thread(futureTask);
thread.start();
try {
//6.获取Callable中的方法的返回值
//get()方法的返回值即为FutureTask构造器参数Callable实现类重写的call()方法的返回值
Integer sum = futureTask.get();
System.out.println("总和为:" + sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
//1.创建一个Callable的实现类
class NumThread implements Callable<Integer>{
//2.实现call()方法,将此线程需要执行的操作声明在call方法中,可以有返回值
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100 ; i++) {
if(i % 2 ==0){
System.out.println(i);
sum += i;
}
}
return sum;
}
}
4.线程池
1.提供指定线程数量的线程池
2.执行指定线程的操作,提供一个实现Runnable接口或Callable接口的实现类对象
线程池的优点
提高响应速度(减少了创建新线程的时间)
降低资源消耗(重复利用线程池中线程,不需要每次都创建)
便于线程管理
corePoolSize:核心池的大小
maximumPoolSize:最大线程数
keepAliveTime:线程没有任务时最多保持多长时间后会终止
public class ThreadPoolTest1 {
public static void main(String[] args) {
//1.提供指定线程数量的线程池
ExecutorService es = Executors.newFixedThreadPool(10);
ThreadPoolExecutor tpe = (ThreadPoolExecutor)es;
//设置线程池的属性
// tpe.setCorePoolSize(15);
// tpe.setKeepAliveTime();
//2.执行指定线程的操作,提供一个实现Runnable接口或Callable接口的实现类对象
es.execute(new NumThread1());//适用于Runnable接口
es.execute(new NumThread2());
// es.submit(Callable callable);//适用于Callable接口
es.shutdown();
}
}
class NumThread1 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 NumThread2 implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 100 ; i++) {
if(i % 2 !=0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
4.线程同步/线程安全
1.出现线程不安全的原因就是因为操作过程中,操作未完成另外一个线程进入导致结果错误
2.如何解决?
当一个线程进行操作的时候,阻止其他线程的进入,就可以解决线程安全的问题
3.在Java中,通过同步机制,来解决线程安全的问题
方式一:同步代码块
synchronized(同步监视器){
需要被同步的代码
}
说明:1.操作共享数据代码,即需要被同步的代码
2.共享数据:多个线程需要共同操作的变量
3.同步监视器:俗称:锁,任何一个类的对象都可以被作为锁
要求:几个线程公用同一把锁
补充:在实现Runnable接口创建多线程的方式中,可以考虑用this来充当同步监视器
在继承Thread类创建多线程的方式中,慎用this充当同步监视器,考虑当前类充当同 步监视器
方式二:同步方法
synchronized
4.同步的方式,解决了线程安全问题
但是操作代码的同时,只能有一个线程参与,其他线程等待,相当于是一个单线程的过程,效率低
总结:关于同步方法
1.同步方法仍然设计到同步监视器,只是不需要我们显示的声明
2.非静态同步方法,同步监视器:this
静态同步方法,同步监视器:当前类本身
1.同步代码块解决线程安全
public class ThreadTest6 {
public static void main(String[] args) {
//继承Threa
Window2 w1 = new Window2();
Window2 w2 = new Window2();
Window2 w3 = new Window2();
w1.start();
w2.start();
w3.start();
//实现Runnable接口
// Window1 w1 = new Window1();
// Thread t1 = new Thread(w1);
// Thread t2 = new Thread(w1);
// Thread t3 = new Thread(w1);
//
// t1.start();
// t2.start();
// t3.start();
}
}
class Window2 extends Thread{
private static int ticket = 100;
private static Object obj = new Object();
@Override
public void run() {
while (true){
// synchronized(obj){//不能使用this,因为此时有三个对象
synchronized(Window2.class){
//Class class = Window2.class
if(ticket > 0){
System.out.println(Thread.currentThread().getName() + "窗口,卖票,票号为:" + ticket);
ticket--;
}else {
break;
}
}
}
}
}
class Window1 implements Runnable{
private int ticket = 100;
// Object obj = new Object();
@Override
public void run() {
while (true){
synchronized(this){
//此时this:唯一的Window1对象
if(ticket > 0){
try {
Thread.sleep(100);
}catch (Exception e){
}
System.out.println(Thread.currentThread().getName() + "窗口,卖票,票号为:" + ticket);
ticket--;
}else {
break;
}
}
}
}
}
2.同步方法解决线程安全
//使用同步方法解决实现Runnable接口安全问题
public class ThreadTest7 {
public static void main(String[] args) {
Window4 w4 = new Window4();
Thread t1 = new Thread(w4);
Thread t2 = new Thread(w4);
Thread t3 = new Thread(w4);
t1.start();
t2.start();
t3.start();
}
}
class Window4 implements Runnable{
private int ticket = 100;
// Object obj = new Object();
@Override
public void run() {
while (true){
show();
if (ticket == 0){
break;
}
}
}
public synchronized void show(){
//同步监视器this
if(ticket > 0){
System.out.println(Thread.currentThread().getName() + "窗口,卖票,票号为:" + ticket);
ticket--;
}
}
}
//使用同步方法解决继承Thread类的线程安全问题
public class ThreadTest8 {
public static void main(String[] args) {
Window6 w1 = new Window6();
Window6 w2 = new Window6();
Window6 w3 = new Window6();
w1.start();
w2.start();
w3.start();
}
}
class Window6 extends Thread{
private static int ticket = 100;
// Object obj = new Object();
@Override
public void run() {
while (true){
show();
if (ticket == 0){
break;
}
}
}
public static synchronized void show(){
//同步监视器:当前类Window.class
if(ticket > 0){
System.out.println(Thread.currentThread().getName() + "窗口,卖票,票号为:" + ticket);
ticket--;
}
}
}
3.Lock锁解决线程安全
1.例题:synchronized和lock的异同
都是可以解决线程安全问题
synchronized机制在执行完相应的同步代码以后,自动的释放同步监视器
lock需要手动的启动同步(lock()),结束同步也需要手动的实现(unlock())
优先使用顺序:Lock---同步代码块----同步方法
public class ThreadTest11 {
public static void main(String[] args) {
Window7 w1 = new Window7();
Thread t1 = new Thread(w1);
Thread t2 = new Thread(w1);
Thread t3 = new Thread(w1);
t1.start();
t2.start();
t3.start();
}
}
class Window7 implements Runnable{
private int ticket = 100;
private ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
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 {
lock.unlock();
}
}
}
}
4.同步机制重写单例模式的懒汉式
//使用同步机制将单例模式中的懒汉式改写为线程安全的
class Bank{
private Bank(){
}
private static Bank instance = null;
public static synchronized Bank getInstance(){
if (instance == null){
instance = new Bank();
}
return instance;
}
}
class Bank1{
private Bank1(){
}
private static Bank1 instance1 = null;
public static Bank1 getInstance(){
//方式一:效率稍差
// synchronized (Bank1.class){
// if (instance1 == null){
// instance1 = new Bank1();
// }
// return instance1;
// }
//方式二:效率稍高
if (instance1 == null){
synchronized (Bank1.class){
if (instance1 == null){
instance1 = new Bank1();
}
return instance1;
}
}
return instance1;
}
}
5.死锁
死锁:不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃
自己需要的同步资源,就形成了线程的死锁
出现死锁后不会出现异常,提示,只是所有线程都处于阻塞状态
解决方法
专门的算法、原则
尽量减少同步资源的定义
尽量避免嵌套同步
public class ThreadTest10 {
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer();
new Thread(){
@Override
public void run() {
synchronized (sb1){
sb1.append("a");
sb2.append("1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (sb2){
sb1.append("b");
sb2.append("2");
System.out.println(sb1);
System.out.println(sb2);
}
}
}
}.start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (sb2){
sb1.append("a");
sb2.append("1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (sb1){
sb1.append("b");
sb2.append("2");
System.out.println(sb1);
System.out.println(sb2);
}
}
}
}).start();
}
}
课后案例
//生产者消费者多线程案例
public class ProductTest {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Producer p1 = new Producer(clerk);
p1.setName("生产者1");
customer c1 = new customer(clerk);
c1.setName("消费者1");
customer c2 = new customer(clerk);
c2.setName("消费者2");
p1.start();
c1.start();
c2.start();
}
}
class Producer extends Thread{
private Clerk clerk;
public Producer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":生产者生产:");
while (true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.produceProduct();
}
}
}
class customer extends Thread{
private Clerk clerk;
public customer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":消费者开始消费:");
while (true){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.consumeProduct();
}
}
}
class Clerk{
private int productCount = 0;
//生产产品
public synchronized void produceProduct() {
if (productCount < 20){
productCount++;
System.out.println(Thread.currentThread().getName() + "生产者1开始生产第" + productCount + "个产品");
notify();
}else {
//等待
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//消费产品
public synchronized void consumeProduct() {
if(productCount > 0){
System.out.println(Thread.currentThread().getName() + ":消费者开始消费第:" + productCount + "个产品");
productCount--;
notify();
}else{
//等待
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
class Clerk{
private int productCount = 0;
//生产产品
public synchronized void produceProduct() {
if (productCount < 20){
productCount++;
System.out.println(Thread.currentThread().getName() + "生产者1开始生产第" + productCount + "个产品");
notify();
}else {
//等待
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//消费产品
public synchronized void consumeProduct() {
if(productCount > 0){
System.out.println(Thread.currentThread().getName() + ":消费者开始消费第:" + productCount + "个产品");
productCount--;
notify();
}else{
//等待
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}