Thread
Runnabel
线程用start启用
Thread三种构造方法:
Thread()
Thread(Runnable target)
Thread(String name)
线程两种实现方式:
1、继承Thread类
1)、自定义MyThread继承Thread类.
2)、MyThread类里面重写run()
3)、创建对象
4)、启动线程
public class MyThread extends Thread{
private String name ;
MyThread(String name){
this.name = name;
}
@Override
//重写run()方法
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("我是"+name+"线程"+i);
}
}
}
public class Test {
public static void main(String[] args) {
MyThread thread1 = new MyThread("No.1");
MyThread thread2 = new MyThread("No.2");
thread1.start();
thread2.start();
}
}
方法:
1)、获得名字:
getName()
Thread.currentThread().getName()
获得当前运行线程的名字
2)、修改名字:
setName()
2、实现Runnable接口
1)、自定义类MyRunnable实现Runnable接口
2)、重写run()方法
3)、创建MyRunnable类对象
4)、创建Tread类的对象,并把3)步骤的对象作为构造参数传递
public class MyRunnable implements Runnable{
private String name ;
MyThread(String name){
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("我是"+name+"线程"+i);
}
}
}
public class Test {
public static void main(String[] args) {
MyRunnable thread1 = new MyRunnable("No.1");
MyRunnable thread2 = new MyRunnable("No.2");
Thread thd1 = new Thread(thread1);
Thread thd2 = new Thread(thread2);
thd1.start();
thd2.start();
}
}
问:
有了方式1,为什么还来一个方式2呢?
1)、可以避免由于Java单继承带来的局限性
2)、适合多个相同程序的代码区处理一个资源的情况,把线程同程序的代码,数据有效的分离,较好的体现了面向对象的设计思想。
最简单的匿名内部类实现多线程:
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("我是线程" + i);
}
}
}).start();
线程优先级:
getPriority():返回线程对象的优先级
setPriority(int newPriority):更改线程的优先级
优先级:1-10 (小-大) —-默认:5级
存在随机性,多运行几次才会发现效果
线程控制:
1、线程休眠
Thread.sleep(long millis); 毫秒
2、线程加入(等待线程终止)
Thread.join()
3、线程礼让
Thread.yield()
(只是让线程更协调)
4、后台线程(守护线程)
//设置守护线程()
Thread.setDaemon(True);
5、线程中断
Stop(过时了)
Thread.interrupt()
(终止线程,并抛出一个InterruptedException)
面试题:
1、run()和start()的区别?
run():仅仅是封装被线程执行的代码,直接调用是普通方法
start(): 首先启动线程,然后再由jvm去调用线程的run()方法。
2、线程的生命周期
四种状态:
1)、新建:创建线程对象
2)、就绪:有执行资格,没有执行权
3)、运行:有执行资格,有执行权
阻塞:由于一些操作让线程进去改状态,没有执行权
而另一些操作可以把他激活,激活后处于就绪状态
4)、死亡:线程对象编程垃圾,等待被回收