程序 指令和数据的有序集合 静态概念
进程 系统资源分配的基本单位 动态概念
线程 cpu调度和执行的基本单位
一个进程开辟了多个线程,线程的执行顺序由cpu决定,无法认为干预。
继承Thread类
class MyThread extends Thread{
@Override
public void run(){
}
}
new MyThread().start();
实现Runnable接口
class MyRunnable implements Runnable{
@Override
public void run(){
}
}
new Thread(new MyRunnable()).start();
实现Callable接口
class MyCallale implements Callable<Boolean>{
@Override
public Boolean call(){
}
}
ExecutorService es = Executors.newFixedThreadPool(1);
Future<Boolean> res = es.submit(new MyCallable());
boolean flag = res.get();
es.shutdown();
静态代理
interface Marry{
public void marry();
}
class Persion implements Marry{
@Override
public void marry(){
}
}
class WeddingCompany implements Marry{
private Marry target;
public WeddingCompany(Persion persion){
this.target = persion;
}
@Override
public void marry(){
System.out.println("结婚前准备");
target.marry();
System.out.println("结婚后准备");
}
}
WeddingCompany wc = new WeddingCompany(new Persion());
wc.marry();
线程状态
new 新生状态
start 就绪状态
sleep join阻塞状态
执行状态
死亡状态 线程只能启动一次
Thread thread = new Thread(() -> {
for(int i = 0; i < 100; i++){
Thread.sleep(1000);
}
});
Thread.State state = thread.getSate();
System.out.println(s);//NEW
thread.start();
Thread.State state = thread.getSate();
System.out.println(s);//RUNNABLE
//TIMED_WAITING
while(state != Thread.State.TERMINATED){
state = thread.getSate();
System.out.println(s);//TERMINATED
}
线程停止
class MyRunable implements Runnable{
private flag = true;
@Override
public void run(){
while(flag){
System.out.println("running......");
}
}
public void stop(){
this.flag = false;
}
}
MyRunable mr = new MyRunnable();
new Thread(mr).start();
mr.stop;
线程休眠
//不会释放锁
Thread.sleep(1000);
线程礼让
//让线程从运行状态转化为就绪状态
//主动礼让的程序状态从运行状态转化为就绪状态
//未礼让的线程是否执行需要系统决定
class MyRunable implements Runnable{
@Override
public void run(){
System.out.println("start------>");
Thread.yield();
System.out.println("end------>");
}
}
new Thread(new MyRunnable(),"A").start();
new Thread(new MyRunnable(),"B").start();
线程合并
//Vip 线程先执行 执行完毕之后才能继续执行其余线程
class MyRunable implements Runnable{
@Override
public void run(){
for(int i = 0; i < 100; i++){
System.out.println("insert success.........");
}
}
public static void main(String[] args){
Thread myThread = new Thread(new MyRunnable());
myThread.start();
for(int i = 0; i < 100; i++){
System.out.println("insert success.........");
if(i == 50){
myThread.join();
}
}
}
}
线程优先级
Thread thread = new Thread(new MyRunnable());
thread.setPriority(3);
thread.start();
守护线程
Thread thread = new Thread(new MyRunnable());
thread.setDaemon(true);
thread.start();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example HTML5 Document</title>
</head>
<body>
<p>Test</p>
</body>
</html>