线程就是 程序 / 进程 的多条 并发执行路径,彼此不干扰,同时进行而不是顺序执行
public class MyThread extends Thread{
@Override
public void run() { // run 方法用来封装被线程执行的代码
for(int i = 0; i < 50; i++){
System.out.println(getName() + ": " + i); // getName() 返回此线程的名称
}
}
}
MyThread my1 = new MyThread();
MyThread my2 = new MyThread();
my1.setName("高铁"); // 使用指定的线程名字
my2.setName("飞机");
my1.start(); // 启动线程, 然后由 JVM 调用此线程的 run 方法
my2.start();
线程优先级
Java是抢占式调度模型,优先让优先级高的线程使用 CPU,优先级高的线程获取的CPU时间片相对多一些。
线程优先级高仅仅表示,获取CPU时间片的几率高
public final int getPriority() // 返回此线程的优先级
public final void setPriority(int newPriority) // 更改此线程的优先级
System.out.println(Thread.MAX_PRIORITY); // 10
System.out.println(Thread.MIN_PRIORITY); // 1
System.out.println(Thread.NORM_PRIORITY); // 5
线程控制
static void sleep(long millis) // 使当前正在执行的线程暂停 指定毫秒数
void join() // 等这个线程执行完, 别的线程才会执行
void setDaemon(boolean on) // 标记为守护线程
MyThread my1 = new MyThread();
MyThread my2 = new MyThread();
my1.setName("高铁");
my2.setName("飞机");
my1.start();
// try {
// my1.join(); // my1 执行完, my2 才会执行
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
my2.start();
MyThread2 my1 = new MyThread2();
MyThread my2 = new MyThread();
my1.setName("关羽");
my2.setName("张飞");
// 修改主线程的名字为 刘备
Thread.currentThread().setName("刘备");
my1.setDaemon(true); // 当 my2 和 主线程刘备 都结束以后,JVM就会退出, my1不管执没执行完都会结束
my1.start();
my2.start();
for(int i = 0; i < 10; i++){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
多线程的实现方式
1.继承 Thread 类
2.实现 Runnable 接口
public class MyRunnable implements Runnable {
@Override
public void run() {
.....
}
}
MyRunnable my = new MyRunnable();
// Thread(Runnable target)
// Thread(Runnable target,String name)
Thread t1 = new Thread(my,"高铁");
Thread t2 = new Thread(my,"飞机");
t1.start();
t2.start();