多线程
顾名思义,就是多个线程同时运行
线程
就像干活
所以
多线程=同时干多个活
编写多线程有俩种方法
1,继承Thread
2,实现Runnable接口
//继承Thread
public class MyThread extends Thread {
@Override
public void run(){
for (int i =0;i<100;i++){
System.out.println(i);
}
}
}
public class Threada {
public static void main(String[] args) {
MyThread my1 = new MyThread();
MyThread my2 = new MyThread();
// my1.run();
// my2.run();
//
my1.start();
my2.start();
}
}
//实现Runnable
public class MyRunnable implements Runnable{
@Override
public void run() {
for (int i =0;i<100;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
public class MyRunnableDemo {
public static void main(String[] args) {
MyRunnable my = new MyRunnable();
// Thread t1 = new Thread(my);
// Thread t2 = new Thread(my);
Thread t1 = new Thread(my,"高铁");
Thread t2 = new Thread(my,"飞机");
t1.start();
t2.start();
}
}
线程的命名
Thread t1 = new Thread(my,"高铁");
//两种方法
t1.setName("黄");
线程的调度
// 线程的优先级是1到10 Thread.MAX_PRIORITY 10 Thread.MIN_PRIORITY
1 Thread.NORM_PRIORITY 5(默认是5)
// 设置优先级
my1.setPriority(10);
//join():等待进程死亡
my1.start();
my1.join();
my2.start();
my3.start();
//线程my1死亡后my3,my2才可以运行
my1.setName("黄");
my2.setName("红");
Thread.currentThread().setName("白色");
// Thread.currentThread().getName()
// 设置守护线程
my1.setDaemon(true);
my2.setDaemon(true);
//白色死亡后红,黄会接着死亡,运行是同时开始