程序:程序就是一段静态的代码,一串指令,一个静态的对象
进程:就是一个程序执行的过程。进程要同时做几件事时,每一个就是一个线程。
线程:线程是一个程序内部一个执行路径
并行:就是多个CPU跑多个线程
并发:一个CPU跑多个线程
一个线程在被启动死亡后不可以再次被启动。
线程的调度策略
时间片:同优先级先到先使用
抢占式:高优先级会抢占低优先级的执行级,但是不一样。只是说高优先更有可能抢占线程。并不是一定。
设置:当前线程对象..setPriority(num)如此类方式设置。
start与run的区别
start用于启动线程,调用当前线程重写的run方法
run里写着要执行的方法体。
线程的创建方法
1, 继承thread类
threadname1 extands Thread
Thread aa = new threadname1();
2, 实现runable接口
threadname2 implements runable()
thread ab=new threadname2 ();
3, 有返回值类型Callable
需要创建一个futuretask来接收callable的返回值,通过get方法获取。转化成object类型
threadname4 implement callable
public object call throws Exception{}
callable a4=new threadname4();
futuretask tf=new futuretask(a4);
Object ob=ft.get();
4, 线程池
1,缓存线程池
//缓存线程池的大小取决于jvm所能创建的线程数量
//线程池的大小超过了处理任务所需要的线程,会回收空闲的线程,循环使用。
executorservice ecs1=executors.newcatchedthreadpool();
ecs1.execute(thread1); //线程写在thread1那,这是启动线程
2,固定线程
//创建固定线程,没有一个任务就使用一个线程
executorservice ecs2=executors.newfixedthreadpool(num);创建线程的数量
esc2.execute9(thread2);
3,单线程线程池
//每次只有一个线程,任务排队等待线程结束,再跑下一个
executorservice ec3=executors.newsinglethreadexecutor();
ecs3.execute(thread3)
4,定时定长线程池
//定长线程池,支持定时及周期性任务执行。延迟执行。
scheduledexecutorservice secs1=executors.newScheduledthreadpool(num);线程数量
//延迟num秒后执行
secs1.schedule(thread4,num,TimeUnit.SECONDS.);
//延迟numer秒后执行,每num秒执行一次
secs1.scheduleAtFixedRate(thread4,numer,num,TimeUnit.SECONDS.);
线程池的关闭
线程池.shutdown();
5,timer定时线程
Timer t=new Timer();
timer.schedule(task, firstTime, period);
threadname3 extands timertask
第一个参数是 实例化的继承timertask的方法,第二个参数是多长时间后进行运行
第三个参数是,间隔多长时间进行下一次运行。