多线程
多线程:
进程:进程指正在运行的程序。
线程:线程是进程中的一个执行单元,负责当前进程中程序的执行,一个进程中至少有一个线程。一个进程中是可以有多个线程的,这个应用程序也可以称之为多线程程序。
单线程程序:多个任务只能排队依次执行。
多线程程序:多个任务可以同时执行。
程序运行原理:
分时调度:所有线程轮流使用cup,平均分配时间占用的时间。
抢占式调度:优先级高的线程先使用cpu,如果优先级相同,随机选择使用,java就是抢占式调度。
主线程:jvm启动后,必然有一个执行路径(线程)从main方法开始的,一直执行到main方法结束,这个线程在java中称之为主线程。
Thread类:
Thread是程序中的执行线程。java虚拟机允许应用程序并发地运行多个执行程序。
创建线程方式一继承Thread类:
public class MyThread extends Thread {
public void run() {
// 获取线程名称getName()
System.out.println("线程名称为" + getName());
for (int i = 0; i < 20; i++) {
System.out.println("myThread-" + i);
}
}
}
public static void main(String[] args) {
//获取执行当前代码的线程的线程对象.名称
System.out.println(Thread.currentThread().getName());
// 创建新线程
MyThread thread = new MyThread();
// 开启线程
thread.start();
for (int i = 0; i < 20; i++) {
System.out.println("main-" + i);
}
}
创建线程方式--实现Runnable接口:
public class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("thread-0" + i);
}
}
}
public static void main(String[] args) {
// 创建线程任务对象
MyRunnable mr = new MyRunnable();
// 创建Thread类对象
Thread th = new Thread(mr);
// 开启线程
th.start();
for (int i = 0; i < 20; i++) {
System.out.println("main-" + i);
}
}
线程的匿名内部类使用:
public static void main(String[] args) {
/*
new 父类或接口名(){
需要重写的方法
}
*/
//1.创建线程的方式 继承Thread
new Thread(){
public void run() {
System.out.println(getName()+"这是新线程任务");
}
}.start();
//2.实现Runnable接口
new Thread(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName()+"在执行线程任务");
}
}).start();
}