Java多线程

引入包

import java.lang.Thread;

多线程定义

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

执行过程

在这里插入图片描述
在这里插入图片描述

创建线程

在这里插入图片描述

继承Thread

1.引入包Thread
2.自定义子类,extends Thread
3.重写run方法

import java.lang.Thread;

public class MyThread extends Thread{
	public void run() {
		for(int i = 0;i < 5;i++) {
			System.out.println("MyThread: "+i);
		}
	}
}

调用

MyThread m1 = new MyThread();
m1.start();

实现Runnable接口

1.implements Runnable接口
2.重写run方法

public class MyRunnable implements Runnable{
	public void run() {
		for(int i = 0;i < 5;i++) {
			System.out.println("MyRunnable: "+i);
		}
	}
}

1.创建Runnable对象
2.加入Thread对象
3.启动线程

MyRunnable f2 = new MyRunnable();
Thread m2 = new Thread(f2);
m2.start();

Callable和Future

在这里插入图片描述

在这里插入图片描述

import java.util.concurrent.Callable;

public class MyCallable implements Callable<String>{
	public String call() {
		for(int i = 0;i < 5;i++) {
			System.out.println("MyCallable: "+i);
		}
		return "Callable";
	}
}
//创建 Callable 实现类的实例
MyCallable m3 = new MyCallable();
//使用 FutureTask 类来包装 Callable 对象
FutureTask f1 = new FutureTask(m3);//Future包装
//3. 使用 FutureTask 对象作为 Thread 对象的 target 创建并启动新线程。
new Thread(f1).start();//创建线程,启动
//4. 调用 FutureTask 对象的 get() 方法来获得子线程执行结束后的返回值。
System.out.println(f1.get());

在这里插入图片描述

几个方法

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

线程同步

银行卡100元,两个人去同时取这100元,会冲突
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

示例

在这里插入图片描述

package Exer3;

import java.lang.Thread;
public class Text {
	public static void main(String []args) {
		//货架上16个
		Product p = new Product();
		//生产商品100个
		
		//生产进程,一个厂家
			new Thread(()->{
				for(int i = 0;i < 100;i++) {//100商品
					p.create();
				}
			  }
					
		).start();
		
		//顾客 ? 个
			//消费进程,一个消费者
			new Thread(()->{
				while(true) {
					p.cost();
				}
			}).start();
			//消费进程,一个消费者
			new Thread(()->{
				while(true) {
					p.cost();
				}
			}).start();
			
	}
}

package Exer3;


public class Product {
	int num = 0;
	Product(){
		
	}
	public synchronized void create() {
		try {
			if(num>=0&&num<16) {
				num++;
				System.out.println("生产!");
				Thread.sleep(1000);
				this.notifyAll();
				this.wait();
			}else {
				System.out.println("货架满了");
				this.notifyAll();
				this.wait();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public synchronized void cost() {
		try {
			if(num>0) {
				num--;
				System.out.println("买走了!");
				Thread.sleep(1000);
				this.notifyAll();
				this.wait();
			}else {
				System.out.println("货架空了,需要生产");
				this.notifyAll();
				this.wait();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}
  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值