线程的创建和使用
Tread类
- 构造器
- Thread():创建新的Thread对象
- Thread(Runnable target):指定创建线程的目标对象,它实现了Runnable接
- 继承Thread类
- 定义子类继承Thread类。
- 子类中重写Thread类中的run方法。
- 创建Thread子类对象,即创建了线程对象。
- 调用线程对象start方法:启动线程,调用run方法。
Runnable接口
- 实现Runnable接口
- 定义子类,实现Runnable接口。
- 子类中重写Runnable接口中的run方法。
- 通过Thread类含参构造器创建线程对象。
- 将Runnable接口的子类对象作为实际参数传递给Thread类的构造器中。
- 调用Thread类的start方法:开启线程,调用Runnable子类接口的run方法。
方法
getName 获取名字
setName 设置名字
getPriority 获取 优先级
setPriority 设置优先级
sleep 睡眠
interrupt 唤醒
Thread.currentThread 获取当前的线程
public class Three_002 {
public static void main(String[] args) {
继承类的子线程创建
Thread thread= new Three_022();
thread.setName("子线程");
try {
// 线程合并
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.start();
Thread.currentThread().setName("main");
for (int i = 6; i <11;i++ ) {
System.out.println(Thread.currentThread().getName() + i);
//实现类 的子线程创建
Thread t1=new Thread(new Test_0014());
t1.setName("实现类线程");
t1.start();
Thread.currentThread().setName("zhu");
System.out.println("123456");
Test_0014.setIsStop(false);
}
}
}
class Three_022 extends Thread{
@Override
public void run() {
for (int i = 1; i < 5;i++) {
System.out.println(this.getName()+i);
}
while (true) {
try {
// 睡眠
Thread.sleep(0);
} catch (InterruptedException e) {
e.printStackTrace();
}SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yy,MM,dd,HH:mm:ss");
String format = simpleDateFormat.format(new Date());
System.out.println(getName()+"~~~~~~~~~~~~~~~~~~~~~~~"+format);
// }
}
}
class Test_0014 implements Runnable {
static boolean isStop=true;
@Override
public void run() {
while (true){
if (isStop) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yy,MM,dd,HH:mm:ss");
String format = simpleDateFormat.format(new Date());
System.out.println(Thread.currentThread().getName()+ format);
}else {
return;
}
}
}
public static boolean isIsStop() {
return isStop;
}
public static void setIsStop(boolean isStop) {
Test_0014.isStop = isStop;
}
}
优先级
1-10