文章目录
基础概念
-
CPU核心数和线程数的关系
核心数:线程数=1:1 ;使用了超线程技术后—> 1:2 -
CPU时间片轮转机制
又称RR调度,会导致上下文切换 -
什么是进程和线程
- 进程:程序运行资源分配的最小单位,进程内部有多个线程,会共享这个进程的资源
- 线程:CPU调度的最小单位,必须依赖进程而存在。
-
澄清并行和并发
- 并行:同一时刻,可以同时处理事情的能力
- 并发:与单位时间相关,在单位时间内可以处理事情的能力
-
高并发编程的意义、好处和注意事项
- 好处:充分利用cpu的资源、加快用户响应的时间,程序模块化,异步化
- 问题:
线程共享资源,存在冲突;
容易导致死锁;
启用太多的线程,就有搞垮机器的可能
认识Java里的线程
java的多线程无处不在
/**
*类说明:java的多线程无处不在
*/
public class OnlyMain {
public static void main(String[] args) {
//虚拟机线程管理的接口
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
ThreadInfo[] threadInfos =
threadMXBean.dumpAllThreads(false, false);
for(ThreadInfo threadInfo:threadInfos) {
System.out.println("["+threadInfo.getThreadId()+"]"+" "
+threadInfo.getThreadName());
}
}
}
输出:
[4] Signal Dispatcher
[3] Finalizer
[2] Reference Handler
[1] main
新启线程的方式三种
新启线程的方式三种:
- 类Thread
- 接口Runnable
- 接口Callable
/**
* 类说明:如何新建线程
*/
public class NewThread {
/* 扩展自Thread类 */
/* 实现Runnable接口 */
private static class UseRun implements Runnable {
@Override
public void run() {
System.out.println("I am implements Runnable");
}
}
/* 实现Callable接口,允许有返回值 */
private static class UseCall implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("I am implements Callable");
return "CallResult";
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
UseRun useRun = new UseRun();
new Thread(useRun).start();
UseCall useCall = new UseCall();
FutureTask<String> futureTask = new FutureTask<>(useCall);
new Thread(futureTask).start();
System.out.println(futureTask.get());
}
}
打印:
I am implements Runnable
I am implements Callable
CallResult
线程安全停止工作
怎么样才能让Java里的线程安全停止工作呢?
stop()还是interrupt() 、 isInterrupted()、static方法interrupted(),深入理解这些方法
-
线程自然终止:自然执行完或抛出未处理异常
-
stop(),resume(),suspend()已不建议使用,stop()会导致线程不会正确释放资源,suspend()容易导致死锁。
-
java线程是协作式,而非抢占式。调用一个线程的interrupt() 方法中断一个线程,并不是强行关闭这个线程,只是跟这个线程打个招呼,将线程的中断标志位置为true,线程是否中断,由线程本身决定。
-
isInterrupted() 判定当前线程是否处于中断状态。
-
static方法interrupted() 判定当前线程是否处于中断状态,同时中断标志位改为false。
/**
* 类说明:如何安全的中断线程
*/
public class EndThread {
private static class UseThread extends Thread {
public UseThread(String name) {
super(name);
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
while (!isInterrupted()) {
System.out.println(threadName + " is run!");
}
System.out.println(threadName + " interrput flag is " + isInterrupted());
}
}
public static void main(String[] args) throws InterruptedException {
Thread endThread = new UseThread("endThread");
endThread.start();
Thread.sleep(2);
endThread.interrupt();
}
}
打印:
…
endThread is run!
endThread is run!
endThread is run!
endThread interrput flag is true
@Override
public void run() {
String threadName = Thread.currentThread().getName();
while (true) {
System.out.println(threadName + " is run!");
}
// System.out.println(threadName + " interrput flag is " + isInterrupted());
}
如果我们不在run方法中做处理,即使调用了interrupt方法,子线程是不会停止的。
/**
* 类说明:中断Runnable类型的线程
*/
public class EndRunnable {
private static class UseRunnable implements Runnable {
@Override
public void run() {
String threadName = Thread.currentThread().getName();
while (!Thread.currentThread().isInterrupted()) {
System.out.println(threadName + " is run!");
}
System.out.println(threadName + " interrput flag is " + Thread.currentThread().isInterrupted());
}
}
public static void main(String[] args) throws InterruptedException {
UseRunnable useRunnable = new UseRunnable();
Thread endThread = new Thread(useRunnable, "endThread");
endThread.start();
Thread.sleep(1);
endThread.interrupt();
}
}
打印:
…
endThread is run!
endThread is run!
endThread interrput flag is true
方法里如果抛出InterruptedException,线程的中断标志位会被复位成false,如果确实是需要中断线程,要求我们自己在catch语句块里再次调用interrupt()。
/**
* 类说明:抛出InterruptedException异常的时候,要注意中断标志位
*/
public class HasInterrputException {
private static class UseThread extends Thread {
public UseThread(String name) {
super(name);
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
while (!isInterrupted()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println(threadName + " catch interrput flag is " + isInterrupted());
e.printStackTrace();
}
System.out.println(threadName);
}
System.out.println(threadName + " interrput flag is " + isInterrupted());
}
}
public static void main(String[] args) throws InterruptedException {
Thread endThread = new UseThread("HasInterrputEx");
endThread.start();
Thread.sleep(20);
endThread.interrupt();
}
}
打印:
在catch语句块里再次调用interrupt():
打印:
对Java里的线程再多一点点认识
线程常用方法和线程的状态
参考:线程的状态详解
线程只有5种状态。整个生命周期就是这几种状态的切换。
-
run()和start() :run方法就是普通对象的普通方法,只有调用了start()后,Java才会将线程对象和操作系统中实际的线程进行映射,再来执行run方法。
-
yield() :让出cpu的执行权,将线程从运行转到可运行状态,但是下个时间片,该线程依然有可能被再次选中运行。
深入理解run()和start():
/**
*类说明:start和run方法的区别
*/
public class StartAndRun {
public static class ThreadRun extends Thread{
@Override
public void run() {
int i = 90;
while(i>0){
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("I am "+Thread.currentThread().getName()
+" and now the i="+i--);
}
}
}
public static void main(String[] args) {
ThreadRun beCalled = new ThreadRun();
beCalled.setName("BeCalled");
//beCalled.setPriority(newPriority);
beCalled.start();
// beCalled.run();
}
}
打印:
I am BeCalled and now the i=90
I am BeCalled and now the i=89
I am BeCalled and now the i=88
I am BeCalled and now the i=87
I am BeCalled and now the i=86
I am BeCalled and now the i=85
I am BeCalled and now the i=84
…
如果是beCalled.run() ,则打印:
I am main and now the i=90
I am main and now the i=89
I am main and now the i=88
I am main and now the i=87
I am main and now the i=86
I am main and now the i=85
I am main and now the i=84
…
线程的优先级
取值为1~10,缺省为5,但线程的优先级不可靠,不建议作为线程开发时候的手段。
setPriority 方法用于设置线程的优先级。每个线程都有自己的优先级数值,当 CPU 资源紧张的时候,优先级高的线程获得 CPU 资源的概率会更大。请注意仅仅是概率会更大,并不意味着就一定能够先于优先级低的获取。这和摇车牌号一个道理,我现在中签概率是标准的 9 倍,但摇中依然摇摇无期。而身边却时不时的出现第一次摇号就中的朋友。如果在 CPU 比较空闲的时候,那么优先级就没有用了,人人都有肉吃,不需要摇号了。
优先级别高可以在大量的执行中有所体现。在大量数据的样本中,优先级高的线程会被选中执行的次数更多。
Thread 有自己的最小和最大优先级数值,范围在 1-10。如果不在此范围内,则会报错。另外如果设置的 priority 超过了线程所在组的 priority ,那么只能被设置为组的最高 priority 。最后通过调用 native 方法 setPriority0 进行设置。
守护线程
当 JVM 中没有任何一个非守护线程时,所有的守护线程都会进入到 TERMINATED 状态,JVM 退出。
在 Java 中,当没有非守护线程存在时,JVM 就会结束自己的生命周期。而守护进程也会自动退出。守护线程一般用于执行独立的后台业务。比如 JAVA 的垃圾清理就是由守护线程执行。而所有非守护线程都退出了,也没有垃圾回收的需要了,所以守护线程就随着 JVM 关闭一起关闭了。
当你有些工作属于后台工作,并且你希望这个线程自己不会终结,而是随着 JVM 退出时自动关闭,那么就可以选择使用守护线程。
要实现守护线程只能手动设置,在线程 start 前调用 setDaemon 方法。Thread 没有直接创建守护进程的方式,非守护线程创建的子线程都是非守护线程。
和主线程共死,finally不能保证一定执行:
/**
* 类说明:守护线程的使用和守护线程中的finally语句块
*/
public class DaemonThread {
private static class UseThread extends Thread {
@Override
public void run() {
try {
while (!isInterrupted()) {
System.out.println(Thread.currentThread().getName() + " I am extends Thread.");
}
System.out.println(Thread.currentThread().getName() + " interrupt flag is " + isInterrupted());
} finally {
System.out.println("...........finally");
}
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
UseThread useThread = new UseThread();
useThread.setDaemon(true);
useThread.start();
Thread.sleep(1);
// useThread.interrupt();
}
}
打印结果并没有执行finally。
线程间的共享
1. synchronized内置锁
对象锁,锁的是类的对象实例。
类锁 ,锁的是每个类的的Class对象,每个类的的Class对象在一个虚拟机中只有一个,所以类锁也只有一个。
对象锁示例:
/**
* 类说明:演示对象锁和类锁
*/
public class SynClzAndInst {
// 使用类锁的线程
private static class SynClass extends Thread {
@Override
public void run() {
System.out.println("TestClass is running...");
synClass();
}
}
// 使用对象锁的线程
private static class InstanceSyn implements Runnable {
private SynClzAndInst synClzAndInst;
public InstanceSyn(SynClzAndInst synClzAndInst) {
this.synClzAndInst = synClzAndInst;
}
@Override
public void run() {
System.out.println("TestInstance is running..." + synClzAndInst);
synClzAndInst.instance();
}
}
// 使用对象锁的线程
private static class Instance2Syn implements Runnable {
private SynClzAndInst synClzAndInst;
public Instance2Syn(SynClzAndInst synClzAndInst) {
this.synClzAndInst = synClzAndInst;
}
@Override
public void run() {
System.out.println("TestInstance2 is running..." + synClzAndInst);
synClzAndInst.instance2();
}
}
// 锁对象
private synchronized void instance() {
SleepTools.second(3);
System.out.println("synInstance is going..." + this.toString());
SleepTools.second(3);
System.out.println("synInstance ended " + this.toString());
}
// 锁对象
private synchronized void instance2() {
SleepTools.second(3);
System.out.println("synInstance2 is going..." + this.toString());
SleepTools.second(3);
System.out.println("synInstance2 ended " + this.toString());
}
// 类锁,实际是锁类的class对象
private static synchronized void synClass() {
SleepTools.second(1);
System.out.println("synClass going...");
SleepTools.second(1);
System.out.println("synClass end");
}
public static void main(String[] args) {
SynClzAndInst synClzAndInst = new SynClzAndInst();
Thread t1 = new Thread(new InstanceSyn(synClzAndInst));
SynClzAndInst synClzAndInst2 = new SynClzAndInst();
Thread t2 = new Thread(new Instance2Syn(synClzAndInst2));
t1.start();
t2.start();
SleepTools.second(1);
}
}
输出:
TestInstance is running…SynClzAndInst@2d3375e
TestInstance2 is running…SynClzAndInst@a2c7b1
synInstance2 is going…SynClzAndInst@a2c7b1
synInstance is going…SynClzAndInst@2d3375e
synInstance2 ended SynClzAndInst@a2c7b1
synInstance ended SynClzAndInst@2d3375e
此时,Instance2Syn和Instance2Syn传入不是同一个对象,instance和instance2方法执行并没有先后顺序。
当Instance2Syn和Instance2Syn传入同一个对象时
public static void main(String[] args) {
SynClzAndInst synClzAndInst = new SynClzAndInst();
Thread t1 = new Thread(new InstanceSyn(synClzAndInst));
// SynClzAndInst synClzAndInst2 = new SynClzAndInst();
Thread t2 = new Thread(new Instance2Syn(synClzAndInst));
t1.start();
t2.start();
SleepTools.second(1);
}
输出:
TestInstance is running…SynClzAndInst@5c16ceab
TestInstance2 is running…SynClzAndInst@5c16ceab
synInstance is going…SynClzAndInst@5c16ceab
synInstance ended SynClzAndInst@5c16ceab
synInstance2 is going…SynClzAndInst@5c16ceab
synInstance2 ended SynClzAndInst@5c16ceab
此时,两个线程虽然都开启了,但是执行对象synClzAndInst中的instance和instance2方法是有先后顺序的。
类锁示例:
public static void main(String[] args) {
SynClzAndInst synClzAndInst = new SynClzAndInst();
Thread t1 = new Thread(new InstanceSyn(synClzAndInst));
t1.start();
SynClass synClass = new SynClass();
synClass.start();
SleepTools.second(1);
}
输出:
TestInstance is running…SynClzAndInst@5c16ceab
TestClass is running…
synClass going…
synClass end
synInstance is going…SynClzAndInst@5c16ceab
synInstance ended SynClzAndInst@5c16ceab
2. volatile关键字
参考:Java并发-Volatile详解
适合于只有一个线程写,多个线程读的场景,因为它只能确保可见性。
演示volatile无法提供操作的原子性:
/**
* 类说明:演示volatile无法提供操作的原子性
*/
public class VolatileUnsafe {
private static class VolatileVar implements Runnable {
private volatile int a = 0;
@Override
public void run() {
String threadName = Thread.currentThread().getName();
a = a++;
System.out.println(threadName + ":======" + a);
SleepTools.ms(100);
a = a + 1;
System.out.println(threadName + ":======" + a);
}
}
public static void main(String[] args) {
VolatileVar v = new VolatileVar();
Thread t1 = new Thread(v);
Thread t2 = new Thread(v);
Thread t3 = new Thread(v);
Thread t4 = new Thread(v);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
输出:
Thread-0:======0
Thread-3:======0
Thread-1:======0
Thread-2:======0
Thread-0:======2
Thread-1:======4
Thread-3:======4
Thread-2:======2
从输出可以看出,volatile无法提供操作的原子性。
3. ThreadLocal
线程变量。可以理解为是个map,类型 Map<Thread,Integer>
/**
* 类说明:演示ThreadLocal的使用
*/
public class UseThreadLocal {
// 可以理解为 一个map,类型 Map<Thread,Integer>
static ThreadLocal<Integer> threadLaocl = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return 1;
}
};
/**
* 运行3个线程
*/
public void StartThreadArray() {
Thread[] runs = new Thread[3];
for (int i = 0; i < runs.length; i++) {
runs[i] = new Thread(new TestThread(i));
}
for (int i = 0; i < runs.length; i++) {
runs[i].start();
}
}
/**
* 类说明:测试线程,线程的工作是将ThreadLocal变量的值变化,并写回,看看线程之间是否会互相影响
*/
public static class TestThread implements Runnable {
int id;
public TestThread(int id) {
this.id = id;
}
public void run() {
System.out.println(Thread.currentThread().getName() + ":start");
Integer s = threadLaocl.get();// 获得变量的值
s = s + id;
threadLaocl.set(s);
System.out.println(Thread.currentThread().getName() + ":" + threadLaocl.get());
// threadLaocl.remove();
}
}
public static void main(String[] args) {
UseThreadLocal test = new UseThreadLocal();
test.StartThreadArray();
}
}
Thread-0:start
Thread-2:start
Thread-1:start
Thread-1:2
Thread-0:1
Thread-2:3
线程间协作
轮询:难以保证及时性,资源开销很大
等待和通知
wait() 对象上的方法
notify/notifyAll 对象上的方法
等待和通知的标准范式
等待方:
- 获取对象的锁;
- 循环里判断条件是否满足,不满足调用wait方法,
- 条件满足执行业务逻辑
通知方来说
- 获取对象的锁;
- 改变条件
- 通知所有等待在对象的线程
notify和notifyAll应该用谁?
应该尽量使用notifyAll,使用notify因为有可能发生信号丢失的的情况。
示例:
/**
* 类说明:快递实体类
*/
public class Express {
public final static String CITY = "ShangHai";
private int km;/* 快递运输里程数 */
private String site;/* 快递到达地点 */
public Express(int km, String site) {
this.km = km;
this.site = site;
}
/* 变化公里数,然后通知处于wait状态并需要处理公里数的线程进行业务处理 */
public synchronized void changeKm() {
this.km = 101;
notifyAll();
// 其他的业务代码
}
/* 变化地点,然后通知处于wait状态并需要处理地点的线程进行业务处理 */
public synchronized void changeSite() {
this.site = "BeiJing";
notifyAll();
}
public synchronized void waitKm() {
while (this.km <= 100) {
try {
wait();
System.out.println("check km thread["
+ Thread.currentThread().getId() + "] is be notifed.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("the km is"
+ this.km + ",I will change db.");
}
public synchronized void waitSite() {
while (CITY.equals(this.site)) {
try {
wait();
System.out.println("check site thread[" + Thread.currentThread().getId() + "] is be notifed.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("the site is" + this.site + ",I will call user.");
}
}
/**
* 类说明:测试wait/notify/notifyAll
*/
public class TestWN {
private static Express express = new Express(0, Express.CITY);
/* 检查里程数变化的线程,不满足条件,线程一直等待 */
private static class CheckKm extends Thread {
@Override
public void run() {
express.waitKm();
}
}
/* 检查地点变化的线程,不满足条件,线程一直等待 */
private static class CheckSite extends Thread {
@Override
public void run() {
express.waitSite();
}
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 3; i++) {// 三个线程
new CheckSite().start();
}
for (int i = 0; i < 3; i++) {// 里程数的变化
new CheckKm().start();
}
Thread.sleep(1000);
express.changeKm();// 快递地点变化
}
}
输出:
check km thread[15] is be notifed.
the km is101,I will change db.
check km thread[14] is be notifed.
the km is101,I will change db.
check km thread[13] is be notifed.
the km is101,I will change db.
check site thread[12] is be notifed.
check site thread[11] is be notifed.
check site thread[10] is be notifed.
如果将changeKm和changeSite方法中notifyAll()都改成notify(),则输出如下:
check site thread[10] is be notifed.
等待超时模式实现一个连接池
假设 等待时间时长为T,当前时间now+T以后超时
long overtime = now+T;
long remain = T;//等待的持续时间
while(result不满足条件&& remain>0){
wait(remain);
remain = overtime – now;//等待剩下的持续时间
}
return result;
示例:
/**
*类说明:实现了数据库连接的实现
*/
public class SqlConnectImpl implements Connection{
/*拿一个数据库连接*/
public static final Connection fetchConnection(){
return new SqlConnectImpl();
}
...
@Override
public void commit() throws SQLException {
SleepTools.ms(70);
}
...
@Override
public Statement createStatement() throws SQLException {
SleepTools.ms(1);
return null;
}
...
}
/**
* 类说明:实现一个数据库的连接池
*/
public class DBPool {
// 数据库池的容器
private static LinkedList<Connection> pool = new LinkedList<>();
public DBPool(int initalSize) {
if (initalSize > 0) {
for (int i = 0; i < initalSize; i++) {
pool.addLast(SqlConnectImpl.fetchConnection());
}
}
}
// 在mills时间内还拿不到数据库连接,返回一个null
public Connection fetchConn(long mills) throws InterruptedException {
synchronized (pool) {
if (mills < 0) {
while (pool.isEmpty()) {
pool.wait();
}
return pool.removeFirst();
} else {
long overtime = System.currentTimeMillis() + mills;
long remain = mills;
while (pool.isEmpty() && remain > 0) {
pool.wait(remain);
remain = overtime - System.currentTimeMillis();
}
Connection result = null;
if (!pool.isEmpty()) {
result = pool.removeFirst();
}
return result;
}
}
}
// 放回数据库连接
public void releaseConn(Connection conn) {
if (conn != null) {
synchronized (pool) {
pool.addLast(conn);
pool.notifyAll();
}
}
}
}
/**
* 类说明:
*/
public class DBPoolTest {
static DBPool pool = new DBPool(10);
// 控制器:控制main线程将会等待所有Woker结束后才能继续执行
static CountDownLatch end;
public static void main(String[] args) throws Exception {
// 线程数量
int threadCount = 50;
end = new CountDownLatch(threadCount);
int count = 20;// 每个线程的操作次数
AtomicInteger got = new AtomicInteger();// 计数器:统计可以拿到连接的线程
AtomicInteger notGot = new AtomicInteger();// 计数器:统计没有拿到连接的线程
for (int i = 0; i < threadCount; i++) {
Thread thread = new Thread(new Worker(count, got, notGot), "worker_" + i);
thread.start();
}
end.await();// main线程在此处等待
System.out.println("总共尝试了: " + (threadCount * count));
System.out.println("拿到连接的次数: " + got);
System.out.println("没能连接的次数: " + notGot);
}
static class Worker implements Runnable {
int count;
AtomicInteger got;
AtomicInteger notGot;
public Worker(int count, AtomicInteger got, AtomicInteger notGot) {
this.count = count;
this.got = got;
this.notGot = notGot;
}
public void run() {
while (count > 0) {
try {
// 从线程池中获取连接,如果1000ms内无法获取到,将会返回null
// 分别统计连接获取的数量got和未获取到的数量notGot
Connection connection = pool.fetchConn(1000);
if (connection != null) {
try {
connection.createStatement();
connection.commit();
} finally {
pool.releaseConn(connection);
got.incrementAndGet();
}
} else {
notGot.incrementAndGet();
System.out.println(Thread.currentThread().getName() + "等待超时!");
}
} catch (Exception ex) {
} finally {
count--;
}
}
end.countDown();
}
}
}
输出:
worker_22等待超时!
worker_21等待超时!
worker_20等待超时!
worker_38等待超时!
worker_26等待超时!
worker_31等待超时!
worker_11等待超时!
worker_25等待超时!
worker_10等待超时!
worker_17等待超时!
worker_12等待超时!
worker_42等待超时!
worker_37等待超时!
worker_33等待超时!
worker_29等待超时!
worker_18等待超时!
worker_36等待超时!
worker_24等待超时!
worker_16等待超时!
worker_39等待超时!
worker_23等待超时!
worker_19等待超时!
worker_35等待超时!
worker_30等待超时!
worker_14等待超时!
worker_28等待超时!
worker_27等待超时!
worker_34等待超时!
worker_32等待超时!
worker_41等待超时!
worker_40等待超时!
worker_15等待超时!
worker_13等待超时!
worker_2等待超时!
worker_3等待超时!
worker_4等待超时!
worker_5等待超时!
worker_9等待超时!
worker_49等待超时!
worker_47等待超时!
worker_20等待超时!
worker_25等待超时!
worker_11等待超时!
worker_10等待超时!
worker_21等待超时!
worker_26等待超时!
worker_38等待超时!
worker_22等待超时!
worker_31等待超时!
worker_14等待超时!
worker_39等待超时!
worker_17等待超时!
worker_33等待超时!
worker_23等待超时!
worker_19等待超时!
worker_28等待超时!
worker_37等待超时!
worker_29等待超时!
worker_42等待超时!
worker_12等待超时!
worker_36等待超时!
worker_24等待超时!
worker_35等待超时!
worker_16等待超时!
worker_30等待超时!
worker_18等待超时!
worker_34等待超时!
worker_41等待超时!
worker_27等待超时!
worker_32等待超时!
worker_46等待超时!
worker_22等待超时!
worker_28等待超时!
worker_12等待超时!
worker_18等待超时!
worker_42等待超时!
worker_29等待超时!
worker_33等待超时!
worker_17等待超时!
worker_19等待超时!
worker_24等待超时!
worker_25等待超时!
worker_11等待超时!
worker_36等待超时!
worker_35等待超时!
worker_21等待超时!
worker_23等待超时!
worker_39等待超时!
worker_30等待超时!
worker_31等待超时!
worker_34等待超时!
worker_38等待超时!
worker_26等待超时!
worker_10等待超时!
worker_16等待超时!
worker_14等待超时!
worker_26等待超时!
worker_25等待超时!
worker_39等待超时!
worker_11等待超时!
worker_17等待超时!
worker_30等待超时!
worker_34等待超时!
worker_31等待超时!
worker_24等待超时!
worker_19等待超时!
worker_36等待超时!
worker_12等待超时!
worker_23等待超时!
worker_38等待超时!
worker_35等待超时!
worker_21等待超时!
worker_41等待超时!
worker_12等待超时!
worker_23等待超时!
worker_35等待超时!
worker_21等待超时!
worker_19等待超时!
worker_24等待超时!
worker_36等待超时!
worker_38等待超时!
总共尝试了: 1000
拿到连接的次数: 879
没能连接的次数: 121
join()方法
- 面试点:
线程A,执行了线程B的join方法,线程A必须要等待B执行完成了以后,线程A才能继续自己的工作
示例:
/**
* 类说明:演示下join方法的使用
*/
public class UseJoin {
static class JumpQueue implements Runnable {
private Thread thread;// 用来插队的线程
public JumpQueue(Thread thread) {
this.thread = thread;
}
public void run() {
try {
System.out.println(thread.getName() + " will be join before " + Thread.currentThread().getName());
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " terminted.");
}
}
public static void main(String[] args) throws Exception {
Thread previous = Thread.currentThread();// 现在是主线程
for (int i = 0; i < 10; i++) {
// i=0,previous 是主线程,i=1;previous是i=0这个线程
Thread thread = new Thread(new JumpQueue(previous), String.valueOf(i));
System.out.println(previous.getName() + " jump a queue the thread:" + thread.getName());
thread.start();
previous = thread;
}
SleepTools.second(2);// 让主线程休眠2秒
System.out.println(Thread.currentThread().getName() + " terminate.");
}
}
输出:
main jump a queue the thread:0
0 jump a queue the thread:1
main will be join before 0
1 jump a queue the thread:2
0 will be join before 1
2 jump a queue the thread:3
1 will be join before 2
3 jump a queue the thread:4
2 will be join before 3
4 jump a queue the thread:5
3 will be join before 4
5 jump a queue the thread:6
4 will be join before 5
6 jump a queue the thread:7
5 will be join before 6
7 jump a queue the thread:8
6 will be join before 7
8 jump a queue the thread:9
7 will be join before 8
8 will be join before 9
main terminate.
0 terminted.
1 terminted.
2 terminted.
3 terminted.
4 terminted.
5 terminted.
6 terminted.
7 terminted.
8 terminted.
9 terminted.
调用yield() 、sleep()、wait()、notify()等方法对锁有何影响?
面试点:
- 线程在执行yield()以后,持有的锁是不释放的
- sleep()方法被调用以后,持有的锁是不释放的
- 调动方法之前,必须要持有锁。调用了wait()方法以后,锁就会被释放,当wait方法返回的时候,线程会重新持有锁
- 调动方法之前,必须要持有锁,调用notify()方法本身不会释放锁的
sleep 示例:
public class SleepLock {
private Object lock = new Object();
public static void main(String[] args) {
SleepLock sleepTest = new SleepLock();
Thread threadA = sleepTest.new ThreadSleep();
threadA.setName("ThreadSleep");
Thread threadB = sleepTest.new ThreadNotSleep();
threadB.setName("ThreadNotSleep");
threadA.start();
try {
Thread.sleep(1000);
System.out.println(" Main slept!");
} catch (InterruptedException e) {
e.printStackTrace();
}
threadB.start();
}
private class ThreadSleep extends Thread {
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " will take the lock");
try {
synchronized (lock) {
System.out.println(threadName + " taking the lock");
Thread.sleep(5000);
System.out.println("Finish the work: " + threadName);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private class ThreadNotSleep extends Thread {
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " will take the lock time=" + System.currentTimeMillis());
synchronized (lock) {
System.out.println(threadName + " taking the lock time=" + System.currentTimeMillis());
System.out.println("Finish the work: " + threadName);
}
}
}
}
打印:
ThreadSleep will take the lock
ThreadSleep taking the lock
Main slept!
ThreadNotSleep will take the lock time=1582507400499
Finish the work: ThreadSleep
ThreadNotSleep taking the lock time=1582507404498
Finish the work: ThreadNotSleep