最近严重发现了,学习就是一个不断输入,不断输出,不断巩固的过程,而这也恰恰解释了自己过去几年来,一直的输入,却是很少输出,导致很多东西记不住,记不牢的原因。现在希望能一周输出至少1~2篇文章吧,也是对以往的总结与回顾了。
这周第一篇:
1,使用线程的好处与坏处:
好处:1,可以利用多核cpu资源
2,异步处理
坏处:1,可能会造成死锁。死锁的四个条件:1)互斥 2)不可剥夺 3) 请求保持 4)循环等待
2,原子性,可见性,有序性、
3,性能问题,当线程数量远远大于
2,线程与进程:
根据冯洛伊曼计算机模型,我们计算机由输入和输出,存储器,运算器和控制器组成。
当我们写的一个Appcation的静态文件时,javac编译成.class,然后通过类加载到内存时,此时运行中的Appcation就是一个进程。
进程的主要作用就是做资源隔离以及分配内存。
线程是cpu调度的最小单元,一个进程至少有一个线程。
3,线程的使用:
创建,生命周期,开始,停止
线程创建的四种方式:
1.继承Thread
2.实现Runnable,没有返回值
3.实现Callable接口,callable有返回值
4.通过线程池的方式
牛逼一点可以讲一种:本质上都是实现Runnable接口
线程的生命周期
在Thread内有个枚举类,表明了生命状态有6种
public enum State {
/**
* Thread state for a thread which has not yet started.
*/
NEW,
/**
* Thread state for a runnable thread. A thread in the runnable
* state is executing in the Java virtual machine but it may
* be waiting for other resources from the operating system
* such as processor.
*/
RUNNABLE,
/**
* Thread state for a thread blocked waiting for a monitor lock.
* A thread in the blocked state is waiting for a monitor lock
* to enter a synchronized block/method or
* reenter a synchronized block/method after calling
* {@link Object#wait() Object.wait}.
*/
BLOCKED,
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link Object#wait() Object.wait} with no timeout</li>
* <li>{@link #join() Thread.join} with no timeout</li>
* <li>{@link LockSupport#park() LockSupport.park}</li>
* </ul>
*
* <p>A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called <tt>Object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
* that object. A thread that has called <tt>Thread.join()</tt>
* is waiting for a specified thread to terminate.
*/
WAITING,
/**
* Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
* <ul>
* <li>{@link #sleep Thread.sleep}</li>
* <li>{@link Object#wait(long) Object.wait} with timeout</li>
* <li>{@link #join(long) Thread.join} with timeout</li>
* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
* </ul>
*/
TIMED_WAITING,
/**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
TERMINATED;
线程的启动
调用start()方法,而run()方法只是一个实例方法的调用
线程的停止
stop方式,严禁使用stop()方法就行线程的停止,因为它会使正在运行的程序戛然而止,不管有没有线程正在运行中。
通过interrupt(),中断方式,会修改中断标记状态,将false改为true;
唤醒阻塞状态下的线程,并且能被try捕获带中断异常,当异常被捕获到之后,在catch里面会自动的将中断标记复位
thread.isInterrupt() 获取中断标记
interrupted()获取中断标记,然后复位中断标记
线程通信方式:
1,通过共享内存的方式。
2,通过等待通知的方式:wait()/notiy/caodition.await()/condition.signal()