1.线程概述
(进程):正在运行的程序。
目前大部分计算机上安装的都是多任务操作系统,即能同时执行多个应用程序。
在多任务操作系统中,表面上看是支持进程并发执行的,实际上这些进程并不是同时运行的。
(线程)
每个运行的程序都是一个进程,在一个进程中还可以有多个执行单元同时运行,这些执行单元可以看作程序执行的一条条线索,被称为线程。
2.线程的创建
继承Tread类创建多线程
package st.peter.tread; public class MyTread { public void run() { while(true) { System.out.println("MyTread的run方法!"); } } } package st.peter.tread; public class Example01 { public static void main(String[] args) { MyTread myTread = new MyTread(); myTread.run(); while(true) { System.out.println("Main方法在运行!"); } } }继承线程类Thread。start()方法用于启动新线程。
package st.peter.tread; public class MyTread extends Thread{ public void run(){ while(true) { System.out.println("MyTread的run方法!"); } } } package st.peter.tread; public class Example01 { public static void main(String[] args) { MyTread myTread = new MyTread(); //myTread.run(); myTread.start(); while(true) { System.out.println("Main方法在运行!"); } } }实现Runnable创建多线程
通过Thread(Runnable target)构造方法创建线程对象时,只需要为该方法传递一个实现了Runnable接口的实例对象,这样创建的线程将调用实现了Runnable接口中的run()方法运行代码。
package st.peter.tread; public class MyTread implements Runnable{ public void run(){ while(true) { System.out.println("MyTread的run方法!"); } } } package st.peter.tread; public class Example01 { public static void main(String[] args) { MyTread myTread = new MyTread(); Thread threa = new Thread(myTread); //myTread.run(); threa.start(); while(true) { System.out.println("Main方法在运行!"); } } }两种实现多线程方式的对比分析
实现Runnable接口相对于继承Thread类来说,有如下显著的好处:
(1)适合多个相同程序代码的线程去处理同一个资源的情况。
(2)避免由于Java单继承带来的局限性
package st.peter.tread; public class TicketWindow implements Runnable { private int tickets = 100; @Override public void run() { // TODO Auto-generated method stub while(true) { if(tickets>0) { //获取当前线程 Thread th = Thread.currentThread(); //获取当前线程的名字 String th_name = th.getName(); System.out.println(th_name+"正在发售第"+tickets--+"张票"); } } } } package st.peter.tread; public class Example05 { public static void main(String[] args) { TicketWindow tw = new TicketWindow(); new Thread(tw,"窗口1").start(); new Thread(tw,"窗口2").start(); new Thread(tw,"窗口3").start(); new Thread(tw,"窗口4").start(); } }3,线程的生命周期及状态转换
https://blog.csdn.net/qq_41405257/article/details/80587478
4,线程的调度
分时调度
抢占式调度(Java虚拟机默认采用)
5,多线程同步
6,多线程通信