线程
线程的状态
一、Thread类
1、先创建线程类
public class MyThread extends Thread{
@Override
public void run() {
//循环输出1-100之间所有整数
for(int i =1;i<=100;i++){
System.out.println(Thread.currentThread().getName()+"正在运行:"+i);
}
}
}
这里的类要继承Thread类
获取对象的名字
Thread.currentThread().getName()
2、在测试类中进行操作
1>创建MyThread类对象
MyThread myThread1 = new MyThread();
2>线程改名
3>线程启动
4>线程优先级(1~10,数字越大优先级越高)
二、Runnable接口
1、创建一个类实现接口
public class MyRunnable implements Runnable{
@Override
public void run() {
for(int i =1;i<=100;i++){
System.out.println(Thread.currentThread().getName()+"正在运行:"+i);
}
}
}
接口中固有重写方法run()
2、在测试类中进行操作
1>创建对象
MyRunnable myRunnable01 = new MyRunnable();
2>启动线程
在MyRunnable类中没有start()方法,在Runnable接口中也没有start()方法,在MyRunnable类默认继承的父类Object类中也没有start()方法
因为start()方法是Thread类里的方法,而启动线程需要使用Thread类中的start()方法
Thread thread1 = new Thread(myRunnable01,"精神小伙");
Thread thread2 = new Thread(myRunnable01,"漂亮小姐姐");
3>其余操作
与Thread类似
三、共有功能(部分介绍)
1、部分方法
2、加锁synchronized