多线程基础总结

并发/高并发

简单来说,并发是指单位时间内能够同时处理的请求数。默认情况下

Tomcat

可以支持的最大请求数是

150

,也就是同时支持

150

个并发。当超过这个并发数的时候,就会开始导致响应延迟,连接丢失等问

题。

影响服务器吞吐量的因素

硬件

CPU

、内存、磁盘、网络

软件层面

最大化的利用硬件资源

线程数量、

JVM

内存分配大小、网络通信机制(

BIO

NIO

AIO

)、磁盘

IO

线程数量如何提升服务端的并发数量

并发和并行

并行是指两个或者多个事件在同一时刻发生;

并发是指两个或多个事件在同一时间间隔内发生,这个词可以冲宏观和微观两个层面来讲,如果从微观

角度来看。以线程为例,假设当前电脑的

cpu

是单核,但是能不能支持多线程呢?当然也是能的,此时

如果是多线程运行的话,那么

CPU

是通过不断分配时间片的方式来实现线程切换,由于切换的速度足够

快,我们很难感知到卡顿的过程。

Java

中的线程

Runnable

接口

Thread

Callable/Futur

e

带返回值的

Thr

ead

这个工具在哪些场景可以应用

网络请求分发的场景

文件导入

短信发送场景

线程的基础

线程的生命周期

 

线程的启动

->

结束

阻塞

WAITING

TIME_W

AITING

BLOCKED

IO

阻塞

Java

的线程有多少状态:

6

需要注意的是,操作系统中的线程除去

new

terminated

状态,一个线程真实存在的状态,只有:

ready

:表示线程已经被创建,正在等待系统调度分配

CPU

使用权。

running

:表示线程获得了

CPU

使用权,正在进行运算

waiting

:表示线程等待(或者说挂起),让出

CPU

资源给其他线程使用

在加上新建状态和死亡状态,一共

5

线程的启动

new Thr

ead().start(); //

启动一个线程

Thread t1=ne

w Thr

ead()

t1.run(); //

调用实例方法

 

线程的终止

线程什么情况下会终止

run

方法执行结束

volatile jint _interrupted; // Thr

ead.isInterrupted state

interrupt()

的作用

设置一个共享变量的值

true

唤醒处于阻塞状态下的线程。

void

os::interrupt

(

Thread

*

thread

) {

assert

(

Thread::current

()

==

thread

||

Threads_lock

->

owned_by_self

(),

"possibility of dangling Thread pointer"

);

OSThread

*

osthread

=

thread

->

osthread

();

if

(

!

osthread

->

interrupted

()) {

osthread

->

set_interrupted

(

true

);

//

设置一个中断状态

// More than one thread can get here with the same value of osthread,

// resulting in multiple notifications. We do, however, want the store

// to interrupted() to be visible to other threads before we execute

unpark().

OrderAccess::fence

();

ParkEvent

*

const

slp

=

thread

->

_SleepEvent

;

//

如果是

sleep

中,唤醒

if

(

slp

!=

NULL

)

slp

->

unpark

() ;

}

// For JSR166. Unpark even if interrupt status already was set

if

(

thread

->

is_Java_thread

())

((

JavaThread

*

)

thread

)

->

parker

()

->

unpark

();

ParkEvent

*

ev

=

thread

->

_ParkEvent

;

if

(

ev

!=

NULL

)

ev

->

unpark

() ;

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值