进程和线程
进程可以简单的理解为一个可以独立运行的程序单位,它是线程的集合,进程就是有一个或多个线程构成的。而线程是进程中的实际运行单位,是操作系统进行运算调度的最小单位。可理解为线程是进程中的一个最小运行单元。
进程和线程是包含关系,但是多任务既可以由多进程实现,也可以由单进程内的多线程实现,还可以混合多进程+多线程。
-
和多线程相比,多进程的缺点在于:
- 创建进程比创建线程开销大,尤其是在Windows系统上;
- 进程间通信比线程间通信要慢,因为线程间通信就是读写同一个变量,速度很快。
-
而多进程的优点在于:
- 多进程稳定性比多线程高,因为在多进程的情况下,一个进程崩溃不会影响其他进程。
- 而在多线程的情况下,任何一个线程崩溃会直接导致整个进程崩溃。
-
Java多线程编程的特点又在于:
- 多线程模型是Java程序最基本的并发模型;
- 后续读写网络、数据库、Web开发等都依赖Java多线程模型。
普通方法调用和多线程
继承Thread类
//创建线程方式之一:继承Thread类,重写run()方法,调用start()开启线程
//线程不一定立即执行,CPU安排调度
public class TestThread1 extends Thread {
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码" + i);
}
}
public static void main(String[] args) {
//main线程,主线程
//创建一个线程对象
TestThread1 testThread1 = new TestThread1();
//调用start()方法开启线程
testThread1.start();
for (int i = 0; i < 20; i++) {
System.out.println("我在学多线程" + i);
}
}
}
实现runnable接口
//创建线程方法2:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法
public class TestThread2 implements Runnable{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 200; i++) {
System.out.println("我在看代码"+i);
}
}
public static void main(String[] args) {
//main线程,主线程
//创建runnable接口的实现类对象
TestThread2 testThread2 = new TestThread2();
//创建线程对象,通过线程对象开启线程,代理
new Thread(testThread2).start();
for (int i = 0; i < 200; i++) {
System.out.println("我在学多线程"+i);
}
}
}
//多个线程同时操作同一个对象
//买火车票的例子
//发现问题:线程不安全,数据紊乱
public class TestThread3 implements Runnable{
private int ticketNums = 10;
@Override
public void run() {
while (true) {
if (ticketNums<=0) {
break;
}
//模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"票");
}
}
public static void main(String[] args) {
TestThread3 ticket = new TestThread3();
new Thread(ticket,"小明").start();
new Thread(ticket,"小红").start();
new Thread(ticket,"小绿").start();
}
}
//模拟龟兔赛跑
public class Race implements Runnable{
//胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
//模拟兔子休息
if (Thread.currentThread().getName().equals("兔子")&& i%10==0){
try {
Thread.sleep(10);
} 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;
}else if (step>=100){
winner=Thread.currentThread().getName();
System.out.println("Winner is "+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() {
WebDownloder webDownloder = new WebDownloder();
webDownloder.downloader(url,name);
System.out.println("下载了文件名为:"+name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("http://i0.hdslb.com/bfs/archive/bcea92a8382a4b8a1c9f14ccddf47eef3532b516.jpg@412w_232h_1c_100q.jpg","1.jpg");
TestCallable t2 = new TestCallable("http://i0.hdslb.com/bfs/archive/bcea92a8382a4b8a1c9f14ccddf47eef3532b516.jpg@412w_232h_1c_100q.jpg","2.jpg");
TestCallable t3 = new TestCallable("http://i0.hdslb.com/bfs/archive/bcea92a8382a4b8a1c9f14ccddf47eef3532b516.jpg@412w_232h_1c_100q.jpg","3.jpg");
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1 =ser.submit(t1);
Future<Boolean> r2 =ser.submit(t2);
Future<Boolean> r3 =ser.submit(t3);
//获取结果
boolean rs1 =r1.get();
boolean rs2 =r2.get();
boolean rs3 =r3.get();
System.out.println(rs1);
System.out.println(rs2);
System.out.println(rs3);
//关闭服务
ser.shutdownNow();
}
}
//下载器
class WebDownloder{
//下载方法
public void downloader(String url,String name) {
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
静态代理
//静态代理模式
//真实对象和代理对象都要实现同一个接口
//代理对象要代理真实角色
//好处:
//1.代理对象可以做很多真实对象做不了的事情
//2.真实对象专注做自己的事情
public class StaticProxy {
public static void main(String[] args) {
//You you =new You();
//you.HappyMarry();
//WeddingCompany weddingCompany =new WeddingCompany(you);
//weddingCompany.HappyMarry();
new Thread(()-> System.out.println("我爱你")).start();
new WeddingCompany(new You()).HappyMarry();
}
}
interface Marry{
void HappyMarry();
}
//真实角色,你去结婚
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("我要结婚了,开心");
}
}
//代理角色,帮你结婚
class WeddingCompany implements Marry{
//代理谁-》真实目标角色
private Marry target;
public WeddingCompany(Marry target) {
this.target = target;
}
private void after() {
System.out.println("结婚之后,收尾款");
}
private void before() {
System.out.println("结婚之前,布置现场");
}
@Override
public void HappyMarry() {
before();
this.target.HappyMarry();//这是真实对象
after();
}
}
Lamda表达式
为什么用?
- 避免匿名内部类定义过多
- 可以让你的代码看起来简洁
- 去掉一堆没有意义的代码,只留下核心的逻辑
理解Functional Interface(函数式接口)是学习Java8 lambd表达式的关键所在。
函数式接口定义:
- 任何接口,如果只包含唯一一个抽象方法,那么他就是一个函数时接口。
public interface Runnable{
public abstract void run();
}
- 对于函数式接口,我们可以通过lambd表达式来创建该接口的对象。
/*
推导lambda表达式
*/
public class TestLambda {
//3.静态内部类
static class Like2 implements ILike{
@Override
public void lambda() {
System.out.println("I like lambda2.");
}
}
public static void main(String[] args) {
ILike like =new Like();
like.lambda();
like = new Like2();
like.lambda();
//4.局部内部类
class Like3 implements ILike{
@Override
public void lambda() {
System.out.println("I like lambda3.");
}
}
like = new Like3();
like.lambda();
//5.匿名内部类 没有类的名称,必须借助接口或者父类
like = new ILike() {
@Override
public void lambda() {
System.out.println("I like lambda4.");
}
};
like.lambda();
//6.用lambda简化
like = ()->{
System.out.println("I like lambda5.");
};
like.lambda();
}
}
//1.定义一个函数式接口
interface ILike{
void lambda();
}
//2.实现类
class Like implements ILike{
@Override
public void lambda() {
System.out.println("I like lambda.");
}
}
public class TestLambda2 {
public static void main(String[] args) {
ILove love = (int a)->{
System.out.println("I love you->"+a);
};
//简化1:参数类型 多个参数也可,但要都去掉
love = (a)->{
System.out.println("I love you->"+a);
};
//简化2:括号,多个参数要加括号
love = a->{
System.out.println("I love you->"+a);
};
//简化3:花括号(只有一行才可)
love = a-> System.out.println("I love you->"+a);
love.love(520);
}
}
//前提:函数式接口
interface ILove{
void love(int a);
}
线程状态
线程方法
方法 | 说明 |
---|---|
setPriority(int newPriority) | 更改线程的优先级 |
static void sleep (long millis) | 在指定的毫秒数内让当前正在执行的线程休眠 |
void join() | 等待线程终止 |
static void yield | 暂停当前正在执行的线程对象,并执行其他线程 |
void interrupt() | 中断线程,别用这个方式 |
boolean isAlive() | 测试线程是否处于活动状态 |
停止线程
- 不推荐使用stop()、destroy()等方法【已废弃】
- 推荐线程自己停下来
- 建议使用一个标识位进行终止变量,当flag=false,则终止线程运行。
//1.建议线程正常停止-利用次数,不建议死循环
//2.建议使用标识位
//3. 不推荐使用stop()、destroy()等方法【已废弃】
public class TestStop implements Runnable{
//1.设置一个标识位
private boolean flag =true;
@Override
public void run() {
int i =0;
while (flag){
System.out.println("run"+i++);
}
}
//2.设置一个公开的方法停止线程,转换标识位
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i <1000 ; i++) {
System.out.println("main"+i);
if (i == 900) {
testStop.stop();//调用stop()切换标识位,停止线程
System.out.println("线程该停止了");
}
}
}
}
线程休眠
- sleep(时间)指定当前线程阻塞的毫秒数
- sleep存在异常InterruptedException
- sleep时间达到后线程进入就绪状态
- sleep可以模拟网路延时,倒计时等
- 每一个对象都有一个锁,sleep不会释放锁
public class TestSleep {
public static void main(String[] args) {
// try {
// tenDown();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//打印当前系统时间
Date startTime = new Date(System.currentTimeMillis());//获取当前时间
while (true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());//更新当前时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if (num <= 0) {
break;
}
}
}
}
线程礼让
- 礼让线程,让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转为就绪状态
- 让cpu重新调度,礼让不一定成功!看CPU心情
//礼让不一定成功!看CPU心情
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
- 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 <100 ; i++) {
if (i == 5) {
thread.join();//插队
}
System.out.println("main"+i);
}
}
}
观测线程状态
public class TestState {
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();
}
}
System.out.println("****");
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);//New
//观察启动后
thread.start();//启动线程
state = thread.getState();
System.out.println(state);//Run
while (state != Thread.State.TERMINATED){//只要线程不终止,就一直输出状态
Thread.sleep(100);
state = thread.getState();//更新线程状态
System.out.println(state);//输出状态
}
}
}
线程的优先级
//优先级高并一定先执行
public class TestPriority {
public static void main(String[] args) {
//主线程默认优先级
System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
Thread t5 = new Thread(myPriority);
Thread t6 = new Thread(myPriority);
//先设置优先级,再启动
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
// t5.setPriority(-1);
// t5.start();
//
// t6.setPriority(11);
// t6.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority());
}
}
守护进程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不必等待守护线程执行完毕
- 如:后台记录操作日志,监控内存,垃圾回收等
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
Yourself yourself = new Yourself();
Thread thread =new Thread(god);
thread.setDaemon(true);//默认false用户线程
thread.start();
new Thread(yourself).start();
}
}
//上帝
class God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("上帝保佑你");
}
}
}
//你
class Yourself implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("开心地活着");
}
System.out.println("byebye world");
}
}
线程同步
- 并发:同一个对象被多个线程同时操作
- 线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用。
- 锁机制synchronized :当一个线程获得对象的排他锁,独占资源,其他线程必须等待,使用后释放锁即可。
三大不安全案例
//不安全买票
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station, "苦逼的我").start();
new Thread(station, "牛逼的你").start();
new Thread(station, "可恶黄牛").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true;//外部停止方法
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
//判断是否有票
if (ticketNums <= 0) {
flag = false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
牛逼的你拿到9
可恶黄牛拿到10
苦逼的我拿到8
牛逼的你拿到7
苦逼的我拿到6
可恶黄牛拿到7
可恶黄牛拿到5
牛逼的你拿到4
苦逼的我拿到5
可恶黄牛拿到3
苦逼的我拿到2
牛逼的你拿到1
苦逼的我拿到-1
可恶黄牛拿到0
//不安全取钱
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account = new Account(100,"结婚基金");
Drawing you = new Drawing(account,50,"你");
Drawing girlFriend = new Drawing(account,100,"girlFriend");
you.start();
girlFriend.start();
}
}
//账户
class Account{
int money;//余额
String name;//卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行:模拟取款
class Drawing extends Thread{
Account account;//账户
int drawingMoney;//取了多少钱
int nowMoney;//现在还有多少钱
public Drawing(Account account,int drawingMoney,String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
//取钱
@Override
public void run() {
//判断有没有钱
if(account.money-drawingMoney<0){
System.out.println("钱不够了,还取钱!");
return;
}
//sleep放大问题的发生性
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额-你取的钱
account.money = account.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
System.out.println(this.getName()+"手里的钱:"+nowMoney);
}
}
结婚基金余额为:0
结婚基金余额为:-50
你手里的钱:50
girlFriend手里的钱:100
//线程不安全的集合
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());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
9999
同步方法和同步块
- 买票
//同步方法,锁的是this
private synchronized void buy() throws InterruptedException {
//判断是否有票
if (ticketNums <= 0) {
flag = false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
- 取钱
//同步块 锁的对象是变化的
synchronized (account){
//判断有没有钱
if(account.money-drawingMoney<0){
System.out.println("钱不够了,还取钱!");
return;
}
//sleep放大问题的发生性
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额-你取的钱
account.money = account.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
System.out.println(this.getName()+"手里的钱:"+nowMoney);
}
- 集合
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
//测试JUC安全类型的集合
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 10; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(list.size());
}
}
死锁
多个线程互相抱着对方需要的资源,形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup g1 = new Makeup(0,"灰姑娘");
Makeup g2 = new Makeup(1,"白雪公主");
g1.start();
g2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
class Makeup extends Thread{
//需要的资源只有一份,用static
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;//选择
String girlName;//使用化妆品的人
Makeup(int choice,String girlName){
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException {
if(choice==0){
synchronized (lipstick){//获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
Thread.sleep(1000);
// synchronized (mirror){//一秒钟后想获得镜子
// System.out.println(this.girlName+"获得镜子的锁");
// }
}
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+"获得口红的锁");
// }
}
synchronized (lipstick){//一秒钟后想获得口红
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
Lock(锁)
通过显示定义同步锁对象来实现同步。
比较常用的是ReentrantLock,可以显示加锁,释放锁。
Lock | synchronized |
---|---|
显式锁,别忘关锁 | 隐式锁 |
代码块锁 | 代码块锁、方法锁 |
性能较好 | 性能较差 |
Lock>同步代码块(已经进入了方法体,分配了相应资源)>同步方法(在方法体之外)
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 =new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 implements Runnable{
int ticketNums =10;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock();//加锁
if (ticketNums >= 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else {
break;
}
}finally {
lock.unlock();//解锁
}
}
}
}
线程协作
生产者消费者模式
方法 | 作用 |
---|---|
wait() | 表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁 |
wait(long timeout) | 指定等待的毫秒数 |
notify() | 唤醒一个处于等待状态的线程 |
notifyAll() | 唤醒同一个对象上所有调用wait()方法的线程,优秀级别高的线程优先调度 |
管程法
//生产者消费者模型-》利用缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
public class CoTest01 {
public static void main(String[] args) {
SyContainer sy=new SyContainer();
Productor pro=new Productor(sy);
pro.start();
Consumer con = new Consumer(sy);
con.start();
}
}
//生产者
class Productor extends Thread{
SyContainer sycon;
public Productor(SyContainer sycon) {
super();
this.sycon = sycon;
}
public void run() {
for(int i=1;i<100;i++) {
System.out.println("生产第"+i+"个馒头");
sycon.push(new Streamedbun(i));
}
}
}
//消费者
class Consumer extends Thread{
SyContainer sycon;
public Consumer(SyContainer sycon) {
super();
this.sycon = sycon;
}
public void run() {
for(int i=0;i<100;i++) {
System.out.println("消费第"+sycon.pop().id+"个馒头");
}
}
}
//缓冲区
class SyContainer{
Streamedbun[] buns=new Streamedbun[100];
int count = 0; //计数器
//存
public synchronized void push(Streamedbun bun){ //加入synchronized关键字
//加入可以生产条件:需要容器存在空间;不能生产,抛锁等待,避免容器越界错误
if(count==buns.length) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
buns[count] = bun;
count++;
this.notifyAll(); //唤醒所有的等待者
}
//取
public synchronized Streamedbun pop(){ 加入synchronized关键字
//加入可以取的条件,避免容器越界错误
if(count==0) {
try {
this.wait(); //每个对象都有一个wait,将锁抛出,线程阻塞,生产者通知消费解除
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
count--;
Streamedbun bun=buns[count];
this.notifyAll(); //唤醒所有的等待者
return bun;
}
}
//数据(馒头)
class Streamedbun{
int id;
public Streamedbun(int id) {
super();
this.id = id;
}
}
信号灯法
//测试生产者消费者问题:信号灯法,标识位解决
public class CoTest02 {
public static void main(String[] args) {
Tv tv=new Tv();
Player pl=new Player(tv);
Watcher wa=new Watcher(tv);
pl.start();
wa.start();
}
}
//产品-节目
class Tv{
String video;
//T表示演员表演,观众等待
//F表示观众观看,演员等待
boolean flag=true;
//表演
public synchronized void play(String video) {
//演员等待
if(!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}if(!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//表演时刻
System.out.println("表演了"+video);
this.video=video;
//表演完毕,唤醒所有线程
this.notifyAll();
//切换灯
this.flag=!this.flag;
}
//观看
public synchronized void watch() {
//观众等待
if(flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("观看了"+video);
//观看完毕,唤醒所有线程
this.notifyAll();
//换灯
this.flag=!this.flag;
}
}
//生产者-演员
class Player extends Thread{
Tv tv;
public Player(Tv tv) {
super();
this.tv = tv;
}
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) {
super();
this.tv = tv;
}
public void run(){
for (int i=0;i<20;i++) {
tv.watch();
}
}
}
线程池
- 提高响应速度
- 降低资源消耗
- 便于线程管理
corePoolSize(线程池基本大小) | 当向线程池提交一个任务时,若线程池已创建的线程数小于corePoolSize,即便此时存在空闲线程,也会通过创建一个新线程来执行该任务,直到已创建的线程数大于或等于corePoolSize时,(除了利用提交新任务来创建和启动线程(按需构造),也可以通过 prestartCoreThread() 或 prestartAllCoreThreads() 方法来提前启动线程池中的基本线程。) |
maximumPoolSize(线程池最大大小) | 线程池所允许的最大线程个数。当队列满了,且已创建的线程数小于maximumPoolSize,则线程池会创建新的线程来执行任务。另外,对于无界队列,可忽略该参数。 |
keepAliveTime(线程存活保持时间) | 当线程池中线程数大于核心线程数时,线程的空闲时间如果超过线程存活时间,那么这个线程就会被销毁,直到线程池中的线程数小于等于核心线程数。 |
workQueue(任务队列) | 用于传输和保存等待执行任务的阻塞队列。 |
threadFactory(线程工厂) | 用于创建新线程。threadFactory创建的线程也是采用new Thread()方式,threadFactory创建的线程名都具有统一的风格:pool-m-thread-n(m为线程池的编号,n为线程池内的线程编号)。 |
handler(线程饱和策略) | 当线程池和队列都满了,再加入线程会执行此策略。 |
public class TestPool {
public static void main(String[] args) {
//1.创建服务,创建线程池
//newFixedThreadPool 参数:线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//2.关闭连接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
学习视频:狂神说Java