-
什么是线程
一条线程就是一组任务执行序列 -
什么是多线程
某一时间段内并发多个任务执行序列 -
为什么需要多线程
多线程可以“同时”运行多个任务。有更好的使用体验。
- 开启一个线程,方式一
要想开启一个新线程,在继承Thread类之后重写父类中的run方法。
优点: 代码简单,适合编写匿名内部类的形式
缺点:- java代码单继承,不能继承其他类。
- 将这个线程直接固定,不能修改,增加了程序中的耦合性,不利于线程重用。
public class ThreadDemo1 {
public static void main(String[] args) {
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
// 开启线程使用start方法
t2.start();
t1.start();
}
}
class MyThread1 extends Thread {
@Override
public void run() {
for (int i = 0;i<1000;i++){
System.out.println("你不是"+i);
}
}
}
class MyThread2 extends Thread {
@Override
public void run() {
for (int i = 0;i<1000;i++){
System.out.println("我是苍老师"+i);
}
}
}
-
方法二. 实现java.lang.Runable接口
这个接口实现类可以赋值给Thread对象当做线程执行的任务序列用
优点:任务和线程对象分离,耦合性低。
缺点:1. 需要额外的代码实例化任务对象,代码比较多 2. 不继承Thread类,有些方法没有办法直接使用
public class ThreadDemo2 {
public static void main(String[] args) {
MyRunable1 r1 = new MyRunable1();
MyRunable2 r2 = new MyRunable2();
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
class MyRunable1 implements Runnable{
@Override
public void run() {
for (int i = 0;i<1000;i++){
System.out.println(1111111111);
}
}
}
class MyRunable2 implements Runnable{
@Override
public void run() {
for (int i = 0;i<1000;i++){
System.out.println(222222222);
}
}
}
- 线程基本信息
public class ThreadInfoDemo {
public static void main(String[] args) {
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("线程名称"+name);
long id = t.getId();
System.out.println("线程唯一标识"+id);
boolean isAlive = t.isAlive();
System.out.println("是否或者"+isAlive);
boolean isDAemon = t.isDaemon();
System.out.println("是否是守护线程"+isDAemon);
boolean isInterrupted = t.isInterrupted();
System.out.println("是否中断");
int pripority = t.getPriority();
System.out.println("优先级"+pripority);
}
}



