注意:很多多线程是模拟出来的,真正的多线程是指有多个cpu,即多核,如服务器。如果是模拟出来的多线程,即在一个cpu的情况下,cpu只能执行一个代码,因为切换的很快,所以就有同时执行的错觉。
继承Thread类 , 实现Runnable接口, 实现Callable接口
实现步骤:
package com.lesson.demo01;public class TestThread1 extends Thread{ @Override public void run() { //run方法线程体 for (int i = 0; i < 200; i++) { System.out.println("我在看代码--"+i); } } public static void main(String[] args) { //main线程是主线程 TestThread1 testThread1 = new TestThread1(); //调用start方法开启线程 testThread1.start(); for (int i = 0; i < 1000; i++) { System.out.println("我在学习多线程--"+i); } }}
执行结果:
我们发现主线程和子线程是并发交替执行的。
总结:线程开启不一定立即执行,由cpu调度执行。
package com.lesson.demo01;import org.apache.commons.io.FileUtils;import java.io.File;import java.io.IOException;import java.net.URL;public class TestThread2 extends Thread { private String url; private String fileName; public TestThread2(String url, String fileName) { this.url = url; this.fileName = fileName; } @Override public void run() { new WebDownloader().downloader(url,fileName); System.out.println("下载了文件名为:"+fileName); } public static void main(String[] args) { TestThread2 t1 = new TestThread2("https://gimg2.baidu.com/image_search/src=http://1812.img.pp.sohu.com.cn/images/blog/2009/11/18/18/8/125b6560a6ag214.jpg&refer=http://1812.img.pp.sohu.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625039900&t=6bc9b0d4ea6e6aa8f584a5ebe922442a", "1.jpg"); TestThread2 t2 = new TestThread2("https://gimg2.baidu.com/image_search/src=http://youimg1.c-ctrip.com/target/tg/035/063/726/3ea4031f045945e1843ae5156749d64c.jpg&refer=http://youimg1.c-ctrip.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625039900&t=99a6ee2704829aab2262a6f21faf35fb", "2.jpg"); TestThread2 t3 = new TestThread2("https://gimg2.baidu.com/image_search/src=http://2c.zol-img.com.cn/product/124_500x2000/748/ceZOdKgDAFsq2.jpg&refer=http://2c.zol-img.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625039900&t=d1739a242ca207055945a00589c1b025", "3.jpg"); t1.start(); t2.start(); t3.start(); }}class WebDownloader{ public void downloader(String url,String fileName){ try { FileUtils.copyURLToFile(new URL(url),new File(fileName)); } catch (IOException e) { e.printStackTrace(); } }}
实现步骤:
package com.lesson.demo01;
public class TestRunnable1 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("我在看代码--"+i);
}
}
public static void main(String[] args) {
TestRunnable1 testRunnable1 = new TestRunnable1();
//创建线程对象,通过线程对象来开启我们的线程。
new Thread(testRunnable1).start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在学习多线程--"+i);
}
}
}
执行结果
小结:
继承Thread类
实现Runnable接口
我们通过买票需求来发现问题
package com.lesson.demo01;
//多个线程同时操作一个对象//买火车票的例子
public class TestRunnable2 implements Runnable {
private int ticketNums = 10;
@Override
public void run() {
while (true){
if(ticketNums <= 0 ){
break;
}
//模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"--->获得了第"+ticketNums--+"张票");
}
}
public static void main(String[] args) {
TestRunnable2 testRunnable = new TestRunnable2();
new Thread(testRunnable,"小明").start();
new Thread(testRunnable,"小张").start();
new Thread(testRunnable,"黄牛党").start();
}
}
执行结果
我们发现问题,多个线程操作同一个资源的情况下,线程不安全,数据紊乱。
实现步骤
package com.lesson.demo01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestCallable implements Callable {
private String url;
private String fileName;
public TestCallable(String url, String fileName) {
this.url = url;
this.fileName = fileName;
}
@Override
public Boolean call() throws Exception {
new WebDownloader2().downloader(url,fileName);
System.out.println("下载了文件名为:"+fileName);
return true;
}
public static void main(String[] args) throws Exception{
TestCallable call1 = new TestCallable("https://gimg2.baidu.com/image_search/src=http://1812.img.pp.sohu.com.cn/images/blog/2009/11/18/18/8/125b6560a6ag214.jpg&refer=http://1812.img.pp.sohu.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625039900&t=6bc9b0d4ea6e6aa8f584a5ebe922442a", "1.jpg");
TestCallable call2 = new TestCallable("https://gimg2.baidu.com/image_search/src=http://youimg1.c-ctrip.com/target/tg/035/063/726/3ea4031f045945e1843ae5156749d64c.jpg&refer=http://youimg1.c-ctrip.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625039900&t=99a6ee2704829aab2262a6f21faf35fb", "2.jpg");
TestCallable call3 = new TestCallable("https://gimg2.baidu.com/image_search/src=http://2c.zol-img.com.cn/product/124_500x2000/748/ceZOdKgDAFsq2.jpg&refer=http://2c.zol-img.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625039900&t=d1739a242ca207055945a00589c1b025", "3.jpg");
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future s1 = ser.submit(call1);
Future s2 = ser.submit(call2);
Future s3 = ser.submit(call3);
//获取结果
Boolean r1 = s1.get();
Boolean r2 = s2.get();
Boolean r3 = s3.get();
//关闭服务
ser.shutdownNow();
}
}
class WebDownloader2{
public void downloader(String url,String fileName){
try {
FileUtils.copyURLToFile(new URL(url),new File(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
}
好处:
方法 | 说明 |
setPriority(int newPriority) | 更改线程的优先级 |
static void sleep(long mills) |
在指定的毫秒数内让当前正在执行的线程休眠 |
void join() | 等待该线程终止 |
static void yield() | 暂停当前正在执行的线程对象,并执行其他线程 |
void interrupt() | 中断线程,别用这个方式 |
boolean isAlive() | 测试线程是否处于活动状态 |
package com.lesson.demo03;
public class TestStop implements Runnable {
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run-------"+i++);
}
}
private void stop(){
this.flag = false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 500; i++) {
System.out.println("main---"+i);
if(i==400){
testStop.stop();
System.out.println("线程该停止了");
}
}
}
}
执行结果:
package com.lesson.demo03;
//模拟倒计时
public class TestSleep2{
public static void main(String[] args) {
try {
tenDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void tenDown() throws InterruptedException {
int num = 10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if(num<=0){
break;
}
}
}
}
package com.lesson.demo03;
//礼让不一定成功
public class TestYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+"线程停止执行");
}
}
礼让成功执行结果
礼让不成功执行结果
Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞。
package com.lesson.demo03;
//测试Join方法
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("线程vip来了----"+i);
}
}
public static void main(String[] args) throws InterruptedException {
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 0; i < 200; i++) {
if(i == 100){
thread.join();
}
System.out.println("主线程:----"+i);
}
}
}
package com.lesson.demo03;
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("执行完毕");
});
Thread.State state = thread.getState();
System.out.println(state);
thread.start();
state = thread.getState();
System.out.println(state);
while(state != Thread.State.TERMINATED){
Thread.sleep(100);
state = thread.getState();
System.out.println(state);
}
}
}
package com.lesson.demo03;
public class TestPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"---->"+Thread.currentThread().getPriority());
}
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"优先级---->"+Thread.currentThread().getPriority());
TestPriority testPriority = new TestPriority();
Thread t1 = new Thread(testPriority);
Thread t2 = new Thread(testPriority);
Thread t3 = new Thread(testPriority);
Thread t4 = new Thread(testPriority);
Thread t5 = new Thread(testPriority);
Thread t6 = new Thread(testPriority);
t1.start();
t2.setPriority(Thread.MIN_PRIORITY);
t2.start();
t3.setPriority(Thread.NORM_PRIORITY);
t3.start();
t4.setPriority(7);
t4.start();
t5.setPriority(Thread.MAX_PRIORITY);
t5.start();
t6.setPriority(4);
t6.start();
}
}
package com.lesson.demo03;
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
thread.setDaemon(true); //默认是false, 正常线程都是用户线程
thread.start();
new Thread(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 < 36500; i++) {
System.out.println("开心的活着");
}
System.out.println("======goodBye World=======");
}
}
同一个对象被多个线程同时操作。
处理多线程问题时,多个线程访问同一个对象,并且某些线程还想修改这个对象,这时候我们就需要线程同步,线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程在使用。
由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制 synchronized ,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可。存在以下问题:
由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法:synchronized方法和synchronized块。
synchronized方法控制对 "对象" 的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。
缺陷:若将一个大的方法申明为synchronized将会影响效率。
同步块:synchronized(Obj){ }
Obj称之为同步监视器
同步监视器的执行过程
package com.lesson.demo04;
//通过synchronized 方法来解决 购票问题
public class TestSynchronized1 implements Runnable{
private int ticketNums = 10;
private boolean flag = true;
@Override
public void run() {
while(flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void buy() throws InterruptedException {
if(ticketNums <= 0 ){
flag = false;
System.out.println("票不够了");
return ;
}
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+"获得了第"+ticketNums--+"票");
}
public static void main(String[] args) {
TestSynchronized1 test = new TestSynchronized1();
new Thread(test,"小明").start();
new Thread(test,"小黄").start();
new Thread(test,"小黑").start();
}
}
package com.lesson.demo04;
//通过synchronized块来解决取钱问题
public class TestSynchronized2 {
public static void main(String[] args) {
Amount amount = new Amount(100,"123");
Drawing you = new Drawing(amount,50,"my");
Drawing girl = new Drawing(amount,100,"girl");
you.start();
girl.start();
}
}
class Amount{
int money;
String no;
public Amount(int money, String no) {
this.money = money;
this.no = no;
}
}
class Drawing extends Thread{
Amount amount;
int drawingMoney;
public Drawing(Amount amount,int drawingMoney,String name){
super(name);
this.amount = amount;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {
synchronized (amount){
if(amount.money-drawingMoney<0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return ;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
amount.money = amount.money - drawingMoney;
System.out.println(amount.no+"余额为:"+amount.money);
}
}
}
多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形,某一个同步块同时拥有 "两个以上对象的锁" 时,就可能发生死锁问题。
只要想办法破其中的任意一个或多个条件就可以避免死锁发生。
package com.lesson.demo05;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock implements Runnable {
private int ticketNums = 10;
private final ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) {
TestLock testLock = new TestLock();
new Thread(testLock).start();
new Thread(testLock).start();
new Thread(testLock).start();
}
@Override
public void run() {
while (true){
try {
lock.lock();//加锁
if(ticketNums <= 0){
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
} finally {
lock.unlock();//释放锁
}
}
}
}
这是一个线程同步问题,生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件。
方法名 | 作用 |
wait() | 表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁 |
wait(long timeout) | 指定等待的毫秒数 |
notify() | 唤醒一个处于等待状态的线程 |
notifyAll() | 唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调度 |
注意:均是Object类的方法,都只能在同步方法或者同步代码块中使用,否则会抛出异常。
并发写作模型 "生产者/消费者模式" --->管程法
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据
package com.lesson.demo06;
//管程法
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生产者
class Productor extends Thread{
SynContainer synContainer;
public Productor(SynContainer synContainer){
this.synContainer = synContainer;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
synContainer.push(new Chicken(i));
System.out.println("生产了"+i+"只鸡");
}
}
}
//消费者
class Consumer extends Thread{
SynContainer synContainer;
public Consumer(SynContainer synContainer){
this.synContainer = synContainer;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println("消费了第"+ synContainer.pop().id+"只鸡");
}
}
}
//产品
class Chicken{
int id;
public Chicken(int id) {
this.id = id;
}
}
//缓冲区
class SynContainer{
//容器
Chicken[] chickens = new Chicken[10];
//计数器
int count = 0;
//存入
public synchronized void push(Chicken chicken){
//如果容器内的数量满了,则等待消费者消费,生产等待
if(count == chickens.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
//如果没有满,我们就需要把产品丢入到容器中
chickens[count] = chicken;
count++ ;
this.notifyAll();
}
}
//取出
public synchronized Chicken pop(){
Chicken chicken=null;
//如果容器内的数量为0,则消费者等待,
if(count == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
count--;
chicken = chickens[count];
//消费完,通知生产者生产
this.notifyAll();
}
return chicken;
}
}
并发协作模型 "生产者/消费者模式" --->信号灯法
package com.lesson.demo06;
//信号灯法
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
//演员
class Player extends Thread{
TV tv;
public Player(TV tv){
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
this.tv.play("抖音");
}
}
}
//观众
class Watcher extends Thread{
TV tv;
public Watcher(TV tv){
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
this.tv.watch();
}
}
}
//节目
class TV{
String voice; //表演的节目
boolean flag = true;
public synchronized void play(String voice){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.voice = voice;
this.flag = !this.flag;
System.out.println("演员演了:"+voice+"节目");
this.notifyAll();//通知消费者消费
}
public synchronized void watch(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众观看了:"+voice+"节目");
this.notifyAll();
this.flag = !this.flag;
}
}
经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具
JDK5.0起提供了线程池相关API:ExecutorService 和 Executors
真正的线程池接口。常见子类 ThreadPoolExecutor
工具类、线程池的工厂类,用于创建并返回不同类型的线程池
package com.lesson.demo06;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestPool {
public static void main(String[] args) {
//1:创建一个池子
ExecutorService service = Executors.newFixedThreadPool(10);
//2:执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//3:关闭链接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}