1.多线程(Thread)实现方法一(继承Thread接口)
程序是静态的,程序被运行就是进程,是动态的,进程里面最少有一个线程(即便你没有执行线程也会有主线程和gc线程(java垃圾回收机制))
继承Thread重写run方法;
public class TestThread extends Thread{
String url;
String file;
public TestThread(String url, String file) {
this.url = url;
this.file = file;
}
@Override
public void run() {
DownLoad downLoad = new DownLoad();
downLoad.downLoad(url,file);
System.out.println("download:"+file);
}
public static void main(String[] args) {
TestThread testThread1 = new TestThread("https://i1.hdslb.com/bfs/face/83bb511365da513c55aa3d1958524f3b7db40684.jpg@96w_96h_1c.webp","1.jpg");
TestThread testThread2 = new TestThread("https://i1.hdslb.com/bfs/face/83bb511365da513c55aa3d1958524f3b7db40684.jpg@96w_96h_1c.webp","2.jpg");
TestThread testThread3 = new TestThread("https://i1.hdslb.com/bfs/face/83bb511365da513c55aa3d1958524f3b7db40684.jpg@96w_96h_1c.webp","3.jpg");
testThread1.start();
testThread2.start();
testThread3.start();
}
}
class DownLoad{
public void downLoad(String url,String file){
try {
FileUtils.copyURLToFile(new URL(url),new File(file));
} catch (IOException e) {
e.printStackTrace();
System.out.println("download异常");
}
}
}
start() 和 run() 的区别
start()方法是开辟新的线程然后再调用run()方法,与主线程同时进行;run()方法是直接在主线程下执行,执行完了再继续主线程的下一步
2.实现方法二(实现Runnable接口)
实现Runnable接口的方法实际上就是一个静态代理,将Runnable接口实现类对象给Thread代理
//实现方式二 实现Runnable接口 重写run方法,执行线程需要丢入runnable接口实现类,调用start方法
public class TestThread02 implements Runnable {
public void run() {
//run方法体
for (int i = 0; i < 200; i++) {
System.out.println("学习多线程---------");
}
}
public static void main(String[] args) {
//创建runnable接口实现类,通过线程对象来开启我们的线程,代理
new Thread(new TestThread02()).start();
//主线程
for (int i = 0; i < 2002; i++) {
System.out.println("主线程============");
}
}
}
3.并发问题(多个线程操作同一个对象)
public class TestThread03 implements Runnable {
private int ticketNum = 10;//票数
public void run() {
while (true){
if (ticketNum <= 0){
break;
}
//模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->拿到了第"+ticketNum--+"张票");
}
}
public static void main(String[] args) {
new Thread(new TestThread03(),"权俊").start();
new Thread(new TestThread03(),"梓汕").start();
new Thread(new TestThread03(),"志志").start();
}
}
4.多线程实现方法三(实现Callable接口)
//线程创建方式三:实现Callable接口
/**
* callable的好处
* 1.可以定义返回值
* 2.可以抛出异常
*/
public class ThreadCallable implements Callable<Boolean> {
String url;
String file;
public ThreadCallable(String url, String file) {
this.url = url;
this.file = file;
}
@Override
public Boolean call() {
lesson01.DownLoad downLoad = new lesson01.DownLoad();
downLoad.downLoad(url,file);
System.out.println("download:"+file);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThreadCallable testThread1 = new ThreadCallable("https://i1.hdslb.com/bfs/face/83bb511365da513c55aa3d1958524f3b7db40684.jpg@96w_96h_1c.webp","1.jpg");
ThreadCallable testThread2 = new ThreadCallable("https://i1.hdslb.com/bfs/face/83bb511365da513c55aa3d1958524f3b7db40684.jpg@96w_96h_1c.webp","2.jpg");
ThreadCallable testThread3 = new ThreadCallable("https://i1.hdslb.com/bfs/face/83bb511365da513c55aa3d1958524f3b7db40684.jpg@96w_96h_1c.webp","3.jpg");
//创建执行服务
ExecutorService service = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> submit = service.submit(testThread1);
Future<Boolean> submit1 = service.submit(testThread2);
Future<Boolean> submit2 = service.submit(testThread3);
//获取结果
Boolean aBoolean = submit.get();
Boolean aBoolean1 = submit1.get();
Boolean aBoolean2 = submit2.get();
System.out.println(aBoolean);
System.out.println(aBoolean1);
System.out.println(aBoolean2);
//关闭服务
service.shutdownNow();
}
class DownLoad{
public void downLoad(String url,String file){
try {
FileUtils.copyURLToFile(new URL(url),new File(file));
} catch (IOException e) {
e.printStackTrace();
System.out.println("download异常");
}
}
}
}
5.线程五大状态
- 新生状态--------线程一旦创建就进入了新生状态(new)
- 就绪状态---------线程一旦start就进入就绪状态等待cpu调度
- 运行状态---------cpu调度完毕,程序进入运行状态
- 阻塞状态-----------线程进入阻塞状态,阻塞状态结束后回到就绪状态等待cpu调度
- dead---------线程中断或者结束,线程一旦进入死亡状态,就不能再次启动
5.线程停止
不推荐使用JSK提供的stop()、destroy()方法
推荐让线程自己停下来
建议使用一个标志位进行终止变量,当flag = false,则终止线程运行
//测试stop
//1.建议线程正常停止
//2.建议使用标志位---设置一个标志位
//3.不要用stop或者destroy等过时或者JDK不建议使用的方法
public class ThreadStop implements Runnable{
//设置标志位
private volatile boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("Thread.....run-->"+i++);
}
}
//设置一个公开的方法,转换标志位
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
ThreadStop threadStop = new ThreadStop();
new Thread(threadStop).start();
for (int i = 0; i < 1000; i++) {
if (i == 900){
threadStop.stop();//调用stop方法切换标志位停止线程
System.out.println("线程停止");
}
System.out.println("主线程-->"+i);
}
}
}
6.Sleep()(线程休眠)
线程调用sleep方法,线程进入阻塞状态,阻塞状态结束,进入就绪状态,等待cpu调度
每个线程都有一个对象锁,阻塞不会关闭锁
sleep常用:
倒计时
//模拟倒计时
public class ThreadSleep02{
public static void main(String[] args) throws InterruptedException {
tenDown();
}
public static void tenDown() throws InterruptedException {
int num = 10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if (num <= 0){
break;
}
}
}
}
系统时间
public static void main(String[] args){
//获取系统当前时间
Date date = new Date(System.currentTimeMillis());
while (true){
try {
System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date));//格式化时间
Thread.sleep(1000);//线程延时1秒
date = new Date(System.currentTimeMillis());//更新时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
7.yield() 线程礼让
礼让不一定成功,看cpu心情
8.join() 合并线程(插队)
Join合并线程,待此线程完成后,在执行其他线程,其他线程阻塞(可以想象为插队)
public class ThreadJoin implements Runnable {
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("尊贵VIP驾到-->"+i);
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new ThreadJoin());
//主线程
for (int i = 0; i < 100; i++) {
if (i == 50){
thread.start();
thread.join();//尊贵VIP插队
}
System.out.println("卑微主线程-->"+i);
}
}
}
注意
- 线程启动需要时间
- 可以通过延时解决主线程还没被插队,子线程已经启动的情况
9.State 线程状态
public class ThreadState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);//NEW
//观察启动后
thread.start();
state = thread.getState();
System.out.println(state);//Runnable
//只要线程不终止,就一直输出线程状态
while(thread.getState() != Thread.State.TERMINATED){
Thread.sleep(100);
state = thread.getState();//更新线程状态
System.out.println(state);//Runnable
}
}
}
注意一定要注意延时的问题
10.线程优先级(Priority)
线程优先级为1~10,最低是1,最高是10,超出范围报错
默认优先级为5.
使用getPriority() setPriority(int xxx)来改变或获取优先级
优先级低只是意味着获得调度的概率低,并不是优先级低的就不会被调用了,这都是看CPU的调度
public class ThreadPriority {
public static void main(String[] args) {
Priority priority = new Priority();
//主线程
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
Thread t1 = new Thread(priority);
Thread t2 = new Thread(priority);
Thread t3 = new Thread(priority);
Thread t4 = new Thread(priority);
Thread t5 = new Thread(priority);
Thread t6 = new Thread(priority);
//先设置优先级再启动线程
t1.start();
t2.setPriority(3);
t2.start();
t3.setPriority(5);
t3.start();
t4.setPriority(7);
t4.start();
t6.setPriority(Thread.MAX_PRIORITY);
t6.start();
t5.setPriority(9);
t5.start();
}
}
class Priority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
11.守护线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕---------如:main()线程
- 虚拟机不用等待守护线程执行完毕-------如:gc线程(垃圾回收机制)、后台记录操作日志、监控日志等
//守护线程案例
//人生不过三万天
public class ThreadDaemon {
public static void main(String[] args) {
Thread god = new Thread(new God());
Thread you = new Thread(new You());
god.setDaemon(true);//默认是false,也就是默认是用户线程,true为守护线程
god.start();
you.start();
}
}
class God implements Runnable{
@Override
public void run() {
while(true) {
System.out.println("上帝一直保佑你");
}
}
}
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
System.out.println("一直开心地活着");
}
System.out.println("goodbye world-----");
}
}
12.同步锁(syschornize隐式锁)
同步代码块结束后就会释放锁(避免死锁)
案例一:
买票问题
//模拟买车票
//同步方法,锁的是this
public class UnSafeBuyTicket {
public static void main(String[] args) {
Station station = new Station();
new Thread(station,"志志").start();
new Thread(station,"梓汕").start();
new Thread(station,"权俊").start();
}
}
class Station implements Runnable{
private volatile int ticket = 10;//车票
private boolean flag = true;
@Override
public void run() {
//买票
while (flag){
//模拟延时
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Buy();
}
}
//买票的方法
public synchronized void Buy(){
//判断是否有票
if (ticket <= 0){
this.flag = false;
return;
}
System.out.println(Thread.currentThread().getName()+"拿到第"+ticket--+"张票");
}
}
线程休眠不会释放锁,线程休眠模拟延时的位置要注意
案例二:
银行取钱问题
//模拟银行取款
//同步锁的对象是账户,如果锁run方法,锁的对象是银行
//(锁的对象应该选择被增删改的对象,用同步块可以选择任意对象,同步方法默认是this)
public class UnSafeBank {
public static void main(String[] args) {
Account account = new Account("结婚彩礼", 100);
new Thread(new Drawing(account,50,"权俊"),"权俊").start();
new Thread(new Drawing(account,100,"志志"),"志志").start();
}
}
//账户
class Account{
private String name;//卡名
private int money;//余额
public Account(String name, int money) {
this.name = name;
this.money = money;
}
public void setName(String name) {
this.name = name;
}
public void setMoney(int money) {
this.money = money;
}
public String getName() {
return name;
}
public int getMoney() {
return money;
}
}
//模拟取款
class Drawing extends Thread{
Account account;
int nowMoney;
int drawingMoney;
//构造方法
public Drawing(Account account,int drawingMoney,String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {
//取款
//模拟延时
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (account) {
//1.先判断有没有钱
if (account.getMoney() - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + "钱不够,取不了!");
return;
}
account.setMoney(account.getMoney() - drawingMoney);
nowMoney = nowMoney + drawingMoney;
System.out.println(Thread.currentThread().getName() + "手上有" + nowMoney);
System.out.println("账户余额剩下:" + account.getMoney());
}
}
}
注意选择锁的对象是否是增删改的对象
案例三:
不安全的list(ArrayList),原因:下标索引可以被同时操作
//不安全的list
//原因:索引可以被同时操作
public class UnSafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
//list.add(Thread.currentThread().getName());
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
13.死锁
原因:两个对象互相持有对方的锁,等待对方释放
public class DeadLock {
public static void main(String[] args) {
MakeLove g1 = new MakeLove(0,"梓汕");
MakeLove g2 = new MakeLove(1,"志志");
g1.start();
g2.start();
}
}
class Lipstick{
}
class Mirror{
}
class MakeLove extends Thread{
//需要资源只有一份,用static保证只有一份资源
private static Lipstick lipstick = new Lipstick();
private static Mirror mirror = new Mirror();
int choose;//选择
String girlName;//人名
public MakeLove(int choose,String girlName){
this.choose = choose;
this.girlName = girlName;
}
@Override
public void run() {
try {
makeLove();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆
public void makeLove() throws InterruptedException {
if (choose == 0){
synchronized (lipstick) {//拿到口红的锁
System.out.println(this.girlName + "拿到了口红的锁");
Thread.sleep(1000);//拿到口红的锁等待一秒再获取镜子的锁
synchronized (mirror) {
System.out.println(this.girlName + "拿到了镜子的锁");
}
}
}else{
synchronized (mirror) {//拿到口红的锁
System.out.println(this.girlName + "拿到了镜子的锁");
Thread.sleep(1000);//拿到镜子的锁等待一秒再获取镜子的锁
synchronized (lipstick) {
System.out.println(this.girlName + "拿到了口红的锁");
}
}
}
}
}
解决方法:先释放掉自己的锁再去获取另外的锁
//化妆
public void makeLove() throws InterruptedException {
if (choose == 0){
synchronized (lipstick) {//拿到口红的锁
System.out.println(this.girlName + "拿到了口红的锁");
Thread.sleep(1000);//拿到口红的锁等待一秒再获取镜子的锁
}
synchronized (mirror) {
System.out.println(this.girlName + "拿到了镜子的锁");
}
}else{
synchronized (mirror) {//拿到口红的锁
System.out.println(this.girlName + "拿到了镜子的锁");
Thread.sleep(1000);//拿到镜子的锁等待一秒再获取镜子的锁
}
synchronized (lipstick) {
System.out.println(this.girlName + "拿到了口红的锁");
}
}
}
死锁避免方法
产生死锁的四个必要条件
- 互斥条件:一个资源每次只能被一个进程使用。
- 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺。
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。
上面列出了死锁的四个必要条件,我们只要想办法破除其中的任意一个或多个条件就可以避免死锁发生
14.Lock(显示锁,显式定义)JDK1.5
Lock跟synchronized 差不多,Lock是接口,一般我们用ReentranLock实现类(可重入锁)
public class TestLock {
public static void main(String[] args) {
Station station = new Station();
new Thread(station).start();
new Thread(station).start();
new Thread(station).start();
}
}
class Station implements Runnable{
private static int ticket = 10;
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.lock();//锁上
try {
if (ticket <= 0) {
break;
}
System.out.println(Thread.currentThread().getName() + "-->" + ticket--);
} finally {
lock.unlock();//释放锁
}
}
}
}
注意点,用完之后一定要释放锁,建议使用阿里云p3c代码规范,lock.lock();方法紧接着try代码块,finally的第一句一定是lock.unlock();
15.生产者消费者(管程法)
//测试生产者消费者模型,方法:管程法
//需要:生产者、消费者、产品、缓冲区(容器)
public class TestPC {
public static void main(String[] args) {
SynContainer synContainer = new SynContainer();
new Thread(new Productor(synContainer)).start();
new Thread(new Customer(synContainer)).start();
}
}
//生产者
class Productor implements Runnable{
SynContainer synContainer;
public Productor(SynContainer synContainer) {
this.synContainer = synContainer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("生产了第"+i+"只鸡");
synContainer.push(new Chicken(i));
}
}
}
//消费者
class Customer implements Runnable{
SynContainer synContainer;
public Customer(SynContainer synContainer) {
this.synContainer = synContainer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
Chicken chicken = synContainer.pop();
System.out.println("消费者消费了第"+chicken.id+"只鸡");
}
}
}
//产品
class Chicken{
int id;
public Chicken(int id) {
this.id = id;
}
}
//缓冲区
class SynContainer{
//容器大小
Chicken[] chickens = new Chicken[10];
//计数
int count = 0;
//消费者消费
public synchronized Chicken pop() {
while(count <= 0){//如果没有产品,消费者等待
try {
this.wait();//调用该方法的就是消费者
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果有产品,消费者消费
count--;
Chicken chicken = chickens[count];
//吃完了,生产者可以生产了
this.notify();//消费者继续消费
return chicken;
}
//生产者生产
public synchronized void push(Chicken chicken){
while (count >= chickens.length) {//如果产品满了,生产者等待
try {
this.wait();//调用该方法的就是生产者
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果产品没有满,我们就需要生产产品
chickens[count] = chicken;
count++;
//生产了,可以通知消费者消费了
this.notify();//生产者继续生产
}
}
16.生产者消费者(信号灯法)
//测试消费者生产者。方法:信号灯法
//生产者 消费者
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Thread(new Player(tv),"表演了").start();
new Thread(new Watcher(tv),"观看了").start();
}
}
class Player implements Runnable{
TV tv;
public Player(TV tv){
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
if (i % 2 == 0){
tv.play("卢本伟牛逼!");
}else {
tv.play("不跟你多BB");
}
}
}
}
class Watcher implements Runnable{
TV tv;
public Watcher(TV tv){
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("-->"+tv.watch());
}
}
}
class TV{
private String voice;//节目
private boolean flag = true;//信号灯,默认为真(生产)
//生产
public synchronized void play(String voice){
while (flag){//如果信号灯为真,就生产
this.voice = voice;//生产
this.flag = !flag;//信号灯转换
System.out.println(Thread.currentThread().getName()+voice);
this.notifyAll();//唤醒等待该对象的所有线程(让消费者消费)
}
//否则就等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized String watch(){
while(flag){//如果信号灯为真(不能消费)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.flag = !flag;//信号灯转变
this.notifyAll();//唤醒等待该对象的所有线程(让生产者生产)
return Thread.currentThread().getName()+voice;//消费
}
}
17.线程池
提高性能,利用ExecutorService接口的Executors实现类的静态方法
//测试线程池
public class TestThreadPool {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(()->{
System.out.println(Thread.currentThread().getName());
});
service.execute(()->{
System.out.println(Thread.currentThread().getName());
});
service.execute(()->{
System.out.println(Thread.currentThread().getName());
});
service.shutdownNow();
}
}
浙公网安备 33010602011771号