进程与线程
和线程紧密相关的是程序,程序是指令和数据的有序集合,是一个静态的概念。进程是执行程序的一次执行过程,它是一个动态的概念,是系统资源分配的单位。
通常一个进程中可以有多个线程,一个进程中也至少有一个线程,否则就没有存在的意义,线程是CPU调度和执行的单位。
注意:
-
很多的多线程是模拟出来的,真正的多线程是指有多个cpu,即多核,如服务器。
-
我们一直使用的main()(用户线程)称为主线程,是一切程序的入口,用于执行整个程序。
-
在程序运行时,即使没有自己创建进程,后台也会有多个线程,如主线程,gc线程(垃圾回收)。
继承Thread类
//创建类继承Thread类,重写run()方法,调用start开启线程
public class TestThread01 extends Thread{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("run方法正在执行"+i);
}
}
public static void main(String[] args) {
//创建线程对象,开启线程
TestThread01 t = new TestThread01();
//通过start()方法开启线程时,两个线程交替执行,因为我们电脑都是单核cpu
t.start();
// 通过run()方法调用时,线程分开执行,先执行run()方法
for (int i = 0; i < 20; i++) {
System.out.println("main方法正在执行"+i);
}
}
}
//执行结果如下,注意电脑性能足够好时,可能会导致单个线程执行完,在执行另一个,此时我们只需要加大循环次数即可
main方法正在执行0
main方法正在执行1
main方法正在执行2
main方法正在执行3
main方法正在执行4
main方法正在执行5
main方法正在执行6
main方法正在执行7
main方法正在执行8
main方法正在执行9
main方法正在执行10
main方法正在执行11
main方法正在执行12
main方法正在执行13
main方法正在执行14
main方法正在执行15
run方法正在执行0
run方法正在执行1
run方法正在执行2
run方法正在执行3
run方法正在执行4
run方法正在执行5
run方法正在执行6
run方法正在执行7
run方法正在执行8
run方法正在执行9
run方法正在执行10
run方法正在执行11
调用run(),等于调用一个普通类中的方法,不会创建新线程,和调用普通的方法一样。而调用start(),创建新的线程去执行run()中的代码块,而主线程可以继续执行其他代码,无需等待run()执行完毕。
下载网上图片资源
//注意要想import此包,需下载commons io的jar包,可到网上下载
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestThread02 extends Thread{
private String url;
private String name;
public TestThread02(String url, String name){
this.url = url;
this.name = name;
}
@Override
public void run() {
WebDownLoader webDownLoader = new WebDownLoader();
webDownLoader.downloader(url,name);
//此处输出文件的名字
File tempFile =new File( name.trim());
String fileName = tempFile.getName();
System.out.println("文件名 = " + fileName);
}
public static void main(String[] args) {
TestThread02 t1 = new TestThread02("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic5.nipic.com%2F20100225%2F1399111_094253001130_2.jpg&refer=http%3A%2F%2Fpic5.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1619414382&t=89180496524c3b8137d533ec50cf9a45","C:\\Users\\hasee\\Desktop\\Markdown\\1.jpg");
TestThread02 t2 = new TestThread02("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic5.nipic.com%2F20100225%2F1399111_094253001130_2.jpg&refer=http%3A%2F%2Fpic5.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1619414382&t=89180496524c3b8137d533ec50cf9a45","C:\\Users\\hasee\\Desktop\\Markdown\\2.jpg");
TestThread02 t3 = new TestThread02("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic5.nipic.com%2F20100225%2F1399111_094253001130_2.jpg&refer=http%3A%2F%2Fpic5.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1619414382&t=89180496524c3b8137d533ec50cf9a45","C:\\Users\\hasee\\Desktop\\Markdown\\3.jpg");
//启动线程
t1.start();
t2.start();
t3.start();
}
}
class WebDownLoader {
public void downloader(String url, String name){
try {
//调用FileUtils下的copyURLToFile方法来获取网上资源,传入参数URl以及文件的保存路径
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常");
}
}
}
实现Runnable接口
//通过Runnbale接口实现线程
public class TestThread03 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("run方法正在执行"+i);
}
}
public static void main(String[] args) {
//创建Runnable实现类的对象
TestThread03 testThread03 = new TestThread03();
//通过线程来开启线程
Thread thread = new Thread(testThread03);
thread.start();
for (int i = 0; i < 20; i++) {
System.out.println("main方法正在执行"+i);
}
}
}
线程同步所存在的问题
//实现多个线程操作同一个对象
//购买火车票
//线程并发问题,抢票混乱不同的线程能抢占同一个资源
public class TestThread04 implements Runnable{
private int ticketNums = 10;
@Override
public void run() {
while (true){
if (ticketNums <= 0){
break;
}
//Thread.currentThread().getName()可以获取线程的名字
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"张票");
}
}
public static void main(String[] args) {
TestThread04 testThread04 = new TestThread04();
//当电脑cpu运行太快时,可以通过调用Thread的sleep方法使线程模拟延迟0.1秒
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
new Thread(testThread04,"我").start();
new Thread(testThread04,"你").start();
new Thread(testThread04,"他").start();
}
}
案例-龟兔赛跑
//模拟龟兔赛跑
public class Race implements Runnable{
private static String winner;
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
//给兔子每十步睡觉一会
if (Thread.currentThread().getName().equals("兔子")&& i % 10 == 0){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boolean flag = gameOver(i);
if (flag){
break;
}
System.out.println(Thread.currentThread().getName() + "跑了" + i + "步");
}
}
//判断游戏是否结束了
private boolean gameOver(int step){
if (winner != null){
return true;
}
{
if (step == 100){
winner = Thread.currentThread().getName();
System.out.println(winner + "赢得了比赛");
return true;
}
return false;
}
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
Callable接口实现线程的创建
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//通过Callable接口实现线程的创建
//1.可以定义返回值 2.可以抛出异常
public class TestCallable implements Callable<Boolean> {
private String url; //网络图片地址
private String name; //图片名字
public TestCallable(String url, String name){
this.url = url;
this.name = name;
}
@Override
public Boolean call() {
WebDownLoader1 webDownLoader1 = new WebDownLoader1();
webDownLoader1.downloader(url,name);
//此处输出文件的名字
File tempFile =new File( name.trim());
String fileName = tempFile.getName();
System.out.println("文件名 = " + fileName);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic5.nipic.com%2F20100225%2F1399111_094253001130_2.jpg&refer=http%3A%2F%2Fpic5.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1619414382&t=89180496524c3b8137d533ec50cf9a45","C:\\Users\\hasee\\Desktop\\Markdown\\1.jpg");
TestCallable t2 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic5.nipic.com%2F20100225%2F1399111_094253001130_2.jpg&refer=http%3A%2F%2Fpic5.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1619414382&t=89180496524c3b8137d533ec50cf9a45","C:\\Users\\hasee\\Desktop\\Markdown\\2.jpg");
TestCallable t3 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic5.nipic.com%2F20100225%2F1399111_094253001130_2.jpg&refer=http%3A%2F%2Fpic5.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1619414382&t=89180496524c3b8137d533ec50cf9a45","C:\\Users\\hasee\\Desktop\\Markdown\\3.jpg");
//启动线程
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> s1 = ser.submit(t1);
Future<Boolean> s2 = ser.submit(t2);
Future<Boolean> s3 = ser.submit(t3);
//获取结果
Boolean rs1 = s1.get();
Boolean rs2 = s2.get();
Boolean rs3 = s3.get();
//打印结果
System.out.println(rs1);
System.out.println(rs2);
System.out.println(rs3);
//关闭服务
ser.shutdownNow();
}
}
class WebDownLoader1 {
public void downloader(String url, String name){
try {
//调用FileUtils下的copyURLToFile方法来获取网上资源,传入参数URl以及文件的保存路径
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常");
}
}
}
Lambda表达式实例
public class Lambda1 {
//3.静态内部类
static class Like1 implements ILike{
@Override
public void lambda() {
System.out.println("I Like Lamda1");
}
}
public static void main(String[] args) {
ILike like = new Like();
like.lambda();
like = new Like1();
like.lambda();
//4.局部内部类
class Like2 implements ILike{
@Override
public void lambda() {
System.out.println("I Like Lamda2");
}
}
like = new Like2();
like.lambda();
//5.匿名内部类 没有类的名称,必须要借助接口或者父类
like = new ILike() {
@Override
public void lambda() {
System.out.println("I Like Lamda3");
}
};
like.lambda();
//6.Lambda简化
/*like = () -> {
System.out.println("I Like Lamda4");
};*/
//Lambda优化
//1.Lambda只有一行代码的时候才能简化成一行 2.函数有参数时,无论几个都可以去掉参数类型,一个时可以去掉()
like = () -> System.out.println("I Like Lamda4");
like.lambda();
}
}
//1.定义一个函数式接口 函数式接口:一个接口里只含一个抽象方法
interface ILike{
void lambda();
}
//2.实现类
class Like implements ILike{
@Override
public void lambda() {
System.out.println("I Like Lamda");
}
}
lock锁
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
public static void main(String[] args) {
BuyTickets buyTickets = new BuyTickets();
new Thread(buyTickets).start();
new Thread(buyTickets).start();
new Thread(buyTickets).start();
}
}
class BuyTickets implements Runnable{
int ticketNums = 10;
//定义lock锁
private final ReentrantLock reentrantLock = new ReentrantLock();
@Override
public void run() {
while (true){
reentrantLock.lock(); //加锁
try {
if(ticketNums > 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else {
break;
}
}finally {
reentrantLock.unlock(); //解锁
}
}
}
}
生产者和消费者-管程法
//测试生产者和消费者模型-》 利用缓冲区解决 (管程法)
public class TestPC {
public static void main(String[] args) {
synContainer c = new synContainer();
new Producer(c).start();
new Consumer(c).start();
}
}
//生产者
class Producer extends Thread{
synContainer container;
public Producer(synContainer container){
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Chicken(i));
System.out.println("生成了" + i + "只鸡");
}
}
}
//消费者
class Consumer extends Thread{
synContainer container;
public Consumer(synContainer container){
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了" + container.pop().id + "只鸡");
}
}
}
//产品
class Chicken{
int id;//编号
public Chicken(int id) {
this.id = id;
}
}
//缓冲区
class synContainer{
//容器大小
Chicken[] chickens = new Chicken[10];
//定义计数器
int count;
//生成者生产产品
public synchronized void push(Chicken chicken){
//如果容器满了,就需要等待消费者消费
if (count == chickens.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果容器没满,就需要丢入产品
chickens[count] = chicken;
count++;
this.notifyAll();
}
//消费者消费产品
public synchronized Chicken pop(){
//判断是否能够消费
if (count == 0){
//等待生产者,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//吃完了,通知生产着生产
this.notifyAll();
return chicken;
}
}
生产者和消费者-信号灯法
//测试生产者消费者问题2:信号灯法,通过(flag)标志位解决
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++) {
if(i%2==0){
this.tv.Play("快乐大本营播放中");
}else {
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++) {
tv.Watch();
}
}
}
//产品-->节目
class TV{
//演员表演,观众等待 真
//观众观看,演员等待 假
String voice; //表演的节目
boolean flag = true; //默认为真
//表演v
public synchronized void Play(String voice){
if (!flag){ //演员等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了:"+voice);
//通知观众观看
this.notifyAll(); //通知唤醒
this.voice = voice;
this.flag = !this.flag;
}
//观看
public synchronized void Watch(){
if (flag){ //观众等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众观看了:"+voice);
//通知演员表演
this.notifyAll();
this.flag = !this.flag;
}
}