一、线程
1、什么叫线程
(1)CPU进行调度的最小单位
(2)进程:运行中的运用
(3)一个进程中至少一条线程,该线程由JVM发起,称之为主线程。
(4)线程的生命周期
1)创建线程对象: 新生 new born
2)调用start方法后: 就绪 ready
3)CPU调度后: 运行running 阻塞 blocked(sleep/wait(100)->notify)
阻塞状态正常结束后,进入就绪态。
4)run方法结束 : 死亡 dead(自然死亡:让循环条件不成立)
(5)如何开启线程
例如:
public class Demo {
static class Task extends Thread{
private int begin;
private int end;
public Task(int begin, int end) {
this.begin = Math.min(begin,end);
this.end = Math.max(begin, end);
}
@Override
public void run() {
for (int i = begin; i <=end ; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2)自定义类继承 Thread
static class Task2 extends Thread{
private int begin;
private int end;
public Task2(int begin, int end) {
this.begin = Math.min(begin,end);
this.end = Math.max(begin, end);
}
@Override
public void run() {
for (int i = begin; i <=end ; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
(5)线程池
// 缓存线程池: 小型任务
ExecutorService esc = Executors.newCachedThreadPool();
//固定线程池:中大型任务
ExecutorService esf = Executors.newFixedThreadPool(10);
/ /单线程池
ExecutorService esc1= Executors.newSIngleThreadPool();
//定时任务线程池
ScheduledExecutorService ess = Executors.newScheduledThreadPool(10);
Class MyCall implement Callable<T>{
//自定义属性
。。。
//自定义方法
....
@Override
Public T call(){
...
}
}
Mycall mc = new MyCall(..)
Future <T>fu = esf.submit(mc);
T t = fu.get();
二、锁

(1)分类:
1)乐观锁
2)悲观锁
a . 共享锁: 读锁
b. 排他锁:写锁
3)公平锁,非公平锁
(2)synchronized: 悲观排他公平锁
1)同步方法
Public synchronized void show(){
This.wait([ int millisec]);
....
This.nodifyaa(); / this.notifyAll();
}
锁为当前对象
2)同步代码块
Synchronized(locker){
Locked.wait ([int millisec]);
...
This.nodify(); / this.notifyAll(
}
3)Lock lock = new ReentrantLock(boolean fair);悲观排他true公平,false不公平
Lock lock = new ReentrantLock();悲观排他非公平锁
Condition cond = lock.newCondution();
Try{
Lock.lockInteruptedly();
Cond.await([int millisec])
}catch(...){
....
}finally{
Lock.unlock();
}
4)读写锁
ReentrantReadWriteLock rw = new RReentrantRead
ReentrantReadWriteLock.Readlock readlock = rw.readlock()’
ReentrantReadWriteLock.WriteLock writelock = rw.writelock();
本文深入探讨了线程的概念,包括线程的生命周期、如何开启线程以及线程池的使用。同时,详细解析了不同类型的锁机制,如乐观锁、悲观锁、共享锁和排他锁,并介绍了synchronized关键字及Lock接口的使用方法。
790

被折叠的 条评论
为什么被折叠?



