多线程是并发机制的一种手段。线程运行是异步的。更多理论知识参考:进程与线程
-
首先了解进程与线程的关系。
进程:进程是系统进行资源分配的最小单位。
线程:线程是cpu进行调度(程序执行)的最小单位。
进程好比pc上正在运行qq程序,线程好比你一边和好有在聊天框发信息,一边进行视频。 -
多线程与多进程
多进程操作系统同时运行多个任务(应用程序)
多线程一个程序里运行多个执行流。
java中创建线程的方式
1.实现Runnable接口
package EasyDemo;
public class MyThreadA implements Runnable {
private String name;//共享变量
public MyThreadA(String name) {
this.name = name;
}
@Override
public void run() {
//重写run方法,作为线程的操作主体
for(int i=0;i<8;i++) {
System.out.println(name+"----i="+i);
}
}
}
package EasyDemo;
public class TestA {
public static void main(String[] args) {
MyThreadA t1 = new MyThreadA("线程1");
MyThreadA t2 = new MyThreadA("线程2");
Thread thread1 = new Thread(t1);//实例化Thread对象
Thread thread2 = new Thread(t2);
thread1.start();//启动线程
thread2.start();
}
}
2.继承Thread类
package EasyDemo;
public class MyThreadB extends Thread {
private String name;// 共享变量
public MyThreadB(String name) {
this.name = name;
}
@Override
public void run() {
// 重写run方法,作为线程的操作主体
for (int i = 0; i < 8; i++) {
System.out.println(name + "----i=" + i);
}
}
}
package EasyDemo;
public class TestA {
public static void main(String[] args) {
MyThreadA t1 = new MyThreadA("线程1");
MyThreadA t2 = new MyThreadA("线程2");
Thread thread1 = new Thread(t1);//实例化Thread对象
Thread thread2 = new Thread(t2);
thread1.start();//启动线程
thread2.start();
}
}
从程序可以看出,现在的两个线程对象是交错运行的,哪个线程对象抢到了 CPU 资源,哪个线程就可以运行,所以程序每次的运行结果肯定是不一样的,在线程启动虽然调用的是 start() 方法,但实际上调用的却是 run() 方法定义的主体。