一、概念:
1、什么是多任务
多任务就是在同一时间做多件事情,如边吃饭边玩手机等。看起来是多个任务都在做,本质上我们的大脑在同一时间依旧只做了一件件事情
2、什么是程序
程序是指令和数据的有序集合,其本身没有任何运行含义,是一个静态概念
3、什么叫进程
进程是执行程序的一次过程,它是一个动态概念,是系统资源分配的单位
小结:通常在一个进程是包含若干个线程,进程中至少有一个线程,不然没有存在的意义,线程是cpu调度和执行的单位
注:很多线程是我们模拟出来的,真是的线程是只多个cup,即多核。如果模拟出来的多线程,即在一个cpu的情况下,在同一个时间的点,cpu只能执行一个代码,因为切换的很快,所以就会有同时执行的错觉
5、多线程的核心概念
- 线程就是独立的执行路径
- 在程序运行时,即使自己没有创建多线程,后台也会有很多线程
- main()称为主线程,为系统的入口,用于执行整个程序
- 在一个进程中,如果开辟了多个线程,线程的运行和调度由调度器安排调度,调度器与操作系统紧密相关,先后顺序是不能人为干预的。
- 对同一份资源操作时,会存在资源抢夺问题,需要加并发控制
- 线程会带来额外的开销,如cup的调度时间,并发控制等
- 每个线程正在自己的工作内存交互,内存控制不当会造成数据不一
二、多线程的创建
Thread class | 继承Thread |
Runnable Interface | 实现Runnable接口 |
Callable Interface | 实现Callable接口(了解) |
1、自定义线程类,继承Thread类,
重写run()方法,编写线程体,
创建线程对象,调用start()方法启动线程
package com.demo01;
// 多线程 继承Thread
public class TestThread01 extends Thread{
public static void main(String[] args) {
for(int i = 0; i<20; i++){
System.out.println(i+"我正在学习多线程");
}
TestThread01 t = new TestThread01();
t.start();
}
@Override
public void run(){
for(int i=0;i<20;i++){
System.out.println(i+"开启多线程");
}
}
}
注:线程开启不一定马上执行,由cpu调度
2、实现Runnable接口
自定义类实现Runnable接口
重写run()方法,编写线程执行体
创建线程对象,调用start()方法启动线程体
package com.demo01;
//第二种实现Thread的方法 实现Runnable接口
public class TestThread02 implements Runnable{
@Override
public void run(){
for(int i = 0;i < 20; i++){
System.out.println(i+"我在学习多线程");
}
}
public static void main(String[] args) {
for(int i =0;i<20;i++){
System.out.println(i+"正在学习多线程");
}
TestThread02 t1 = new TestThread02();
Thread thread = new Thread(t1);
thread.start();
}
}
3、实现Callable接口(了解)
package com.demo01;
import java.util.concurrent.*;
//创建线程 实现Callable接口
public class TestThread05 implements Callable<Boolean> {
@Override
public Boolean call() throws Exception {
for(int i=1;i<=10;i++){
System.out.println("我正在学习"+i);
}
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestThread05 t = new TestThread05();
// 创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(1);
// 提交执行
Future<Boolean> submit = ser.submit(t);
// 获取结果集
Boolean aBoolean = submit.get();
// 关闭服务
ser.shutdownNow();
}
}
小结:
- 继承Thread类 继承Runnable接口
- 子类继承Thread类具备多线程能力 实现Runnable接口具备多线程能力
- 启动线程:子类对象.start() 启动线程:传入目标对象+Thread对象.start()
- 不建议使用:避免oop单继承的局限性
- 推荐使用:避免单继承的局限性,
同一个对象可以被多个线程使用
三、线程的状态
线程停止
建议线程正常停止-->利用次数,不建议死循环
建议使用标志位-->设置一个标志位
package com.StateThread;
//线程的状态
//使线程停止
public class TestThread06 implements Runnable{
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("线程运行中"+i++);
}
}
// 标志位
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
TestThread06 t = new TestThread06();
new Thread(t).start();
for(int i=0;i<1000;i++){
System.out.println(i);
if(i==900){
System.out.println("线程停止了"+i);
t.stop();
}
}
}
}
线程休眠
package com.StateThread;
//模拟线程休眠
public class TestThread07 implements Runnable{
public static void main(String[] args) {
TestThread07 t = new TestThread07();
new Thread(t).start();
}
@Override
public void run() {
int sum = 10;
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(sum--);
if(sum==0){
break;
}
}
}
}
注:每一个对象都有一个锁,sleep不会释放锁,Thread.sleep(1000) 1千毫米=1秒
线程礼让
package com.StateThread;
//线程礼让
public class TestThread08 implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程执行开始");
Thread.yield();
System.out.println(Thread.currentThread().getName()+"线程执行结束");
}
public static void main(String[] args) {
TestThread08 t = new TestThread08();
new Thread(t,"小明").start();
new Thread(t,"小红").start();
}
}
线程插队
Join合并线程,待线程执行完成后再执行其他线程,其他线程阻塞。可以想象成插队。Thread.join()。
package com.StateThread;
//线程插队
public class TestThread09 implements Runnable{
public static void main(String[] args) throws InterruptedException {
TestThread09 t = new TestThread09();
Thread thread = new Thread(t);
thread.start();
for (int i =0;i<500;i++){
if(i==200){
thread.join();
}
System.out.println("main执行"+i);
}
}
@Override
public void run() {
for(int i =0;i<500;i++){
System.out.println("子线程执行VIP"+i);
}
}
}
观察线程状态
Thread.state()
//观察线程状态
public class TestThread10 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(()->{
for(int i=0;i<5;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("结束");
});
// 线程启动前的状态
Thread.State state = t.getState();
System.out.println(state);
// 线程启动时的状态
t.start();
state = t.getState();
System.out.println(state);
// 线程结束时的状态
while (state != Thread.State.TERMINATED){//只要线程不中止
Thread.sleep(100);
state = t.getState();
System.out.println(state);
}
}
}
线程优先级
线程优先级用数字表示范围从1~10,数字越大优先级越大
要先设置优先级在启动线程
package com.StateThread;
//线程的优先级
public class TestThread11 {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority());
test t = new test();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
Thread t5 = new Thread(t);
// 1
t1.start();
// 2
t2.setPriority(Thread.MAX_PRIORITY);
t2.start();
// 3
t3.setPriority(Thread.MIN_PRIORITY);
t3.start();
// 4
t4.setPriority(6);
t4.start();
// 5
t5.setPriority(8);
t5.start();
}
}
class test implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority());
}
}
注:优先级只是意味着获得调度的概率低,并不是优先级低就不会被调度或被晚调度,这都看cpu的心情,人为是没办法干预cpu的调度的
守护线程
1、线程分为用户线程和守护线程
2、虚拟机必须确保用户线程执行完毕(main(主线程))
3、虚拟机不用等待守护线程执行完毕(gc(垃圾回收))
设置方法为: Thread.setPaemon(ture) 默认为:false
package com.StateThread;
//守护线程
public class TestThread12 {
public static void main(String[] args) {
test1 t1 = new test1();
test2 t2 = new test2();
Thread th = new Thread(t2);
th.setDaemon(true);
th.start();
new Thread(t1).start();
}
}
class test1 implements Runnable{
@Override
public void run() {
for (int i=0;i<36500;i++){
System.out.println("我一直开心的活着");
}
System.out.println("和这个时间说再见了");
}
}
class test2 implements Runnable{
@Override
public void run() {
while (true){
System.out.println("上帝一直保佑着我");
}
}
}
四、线程同步
- 概念:线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,前面线程使用完毕,下一个线程在使用。
- 什么是并发:多个线程操作同一个资源。
- 锁:每一个对象都有一把锁,解决安全问题。
- 形成条件:队列+锁
- 同步方法:这套机制就是synchronized关键字,包括两种方法,synchronized方法和synchronized块
package com.Synchrohized;
public class UnSafeTicket {
public static void main(String[] args) {
ticket t =new ticket();
new Thread(t,"1").start();
new Thread(t,"2").start();
new Thread(t,"3").start();
}
}
//多线程
class ticket implements Runnable{
private boolean flag = true;
private int ticket=100;
@Override
public void run() {
while (flag){
try {
Thread.sleep(100);
buyTicket();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//线程停止
public void stop() {
this.flag = false;
}
//买票
public synchronized void buyTicket() throws InterruptedException {
if(ticket<=0){
stop();
return;
}
System.out.println(Thread.currentThread().getName()+"买到了第"+ticket--+"张票");
}
}
//synchronized代码块的使用
package com.Synchrohized;
public class UnSafeBank {
public static void main(String[] args) {
Account account = new Account(1000,"存款");
people people = new people(account,50);
people people1 = new people(account,100);
people.start();
people1.start();
}
}
class people extends Thread{
Account account;
int quMoney;
int nowMoney;
public people(Account account,int quMoney){
this.account=account;
this.quMoney=quMoney;
}
//取钱
@Override
public void run(){
synchronized (account){
if(account.money-quMoney<0){
System.out.println("钱不够,取不了");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money = account.money-quMoney;
nowMoney = nowMoney + quMoney;
System.out.println(account.name+"余额为"+account.money);
System.out.println(this.getName()+"手上的钱为"+nowMoney);
}
}
}
//账户
class Account{
int money;
String name;
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
当某个对象调用了同步方法时,该对象上的其他同步方法必须等待该同步方法执行完毕后才能被
执行。必须将每个能访问共享资源的方法修饰为synchronized,否则就会出错。
修改例题20.7的代码,将共享资源操作放置在用同一个同步方法中
int num = 10; //设置当前总票数
public synchronized void doit() { //定义同步方法
if(num>0){
try{
Thread.sleep(10);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"---票数"+num--);
}
}
public void run(){
while(true){
doit();
}
}//再run()方法中调用该同步方法