线程基础
1.什么是线程
一条线程就是一组任务执行序列
2.什么是多线程
多线程就是在某一时间段内并发多个任务执行序列
3.为什么需要多线程
有了多线程就可以“同时”运行多个任务,有效利用资源,让使用者有更好的使用体验
由于硬件决定了多个到吗片段不是真正意义上的同事执行,只是模拟这样的操作而已,实际上多个代码片段都是走走停停的,但感官上是同事运行这种执行方式成为“并发”
4.创建线程的两种方式
方式一
public class ThreadDemo1 {
public static void main(String[] args) {
MyThread1 t=new MyThread1();
/*
* 使用thread类对象的start方法开启新线程
* 我们重写的run方法,但是不能调用它
*/
t.start();
}
}
class MyThread1 extends Thread{
/*
* 要想开启一个线程,必须继承Thread类之后
* 重写父类中的run方法
*/
@Override
public void run() {
/*
* run方法中的代码就是开启新线程要执行的任务序列
*/
System.out.println("你是谁");
}
}
方式二
public class ThreadDemo2 {
public static void main(String[] args) {
MyRunnable1 r1=new MyRunnable1();
Thread t1= new Thread(r1);
t1.start();
}
}
/*
* 方式二 实现java.langRunnable接口
* 这个接口实现类可以赋值给Thread对象做线程执行的任务序列用
*/
class MyRunnable1 implements Runnable{
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("就不爱跟你们这些男孩玩");
}
}
}
第一种创建线程的方式的优点在于创建简单,适合使用匿名内部类形式创建
缺点在于:
1.继承冲突,由于java是单继承的,这会导致继承的Thread就无法在继承其他类,很不方便
2.重写run方法相当于直接将线程执行的任务写死在线程中,导致线程与任务之间有一个必然的耦合关系,不利于线程的重用
使用匿名内部类创建线程
public class ThreadDemo3 {
public static void main(String[] args) {
//方式一
Thread t1=new Thread() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.err.println("你谁");
}
}
};
//方式二
Runnable r=new Runnable() {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("你管");
}
}
};
Thread t2=new Thread(r);
t1.start();
t2.start();
}
}
5.获取线程
/**
* static Thread currentThread()
* 这个方法直接返回正在运行的线程的对象
* @author Administrator
*
*/
public class CurrentThreadDemo {
public static void main(String[] args) {
/*
* main()实际上也是一条线程,知识不由程序员创建
*/
// Thread m=Thread.currentThread();
// System.out.println(m);
// dosome();
Thread t=new Thread() {
@Override
public void run() {
dosome();
}
};
//给线程赋一个name
t.setName("Tom");
t.start();
}
public static void dosome() {
Thread t=Thread.currentThread();
System.out.println(t);
}
}
执行结果为:Thread[Tom,5,main]
6.线程信息
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("是否中断:"+isInterrupted);
//优先级
int priority=t.getPriority();
System.out.println("优先级:"+priority);
}
}