package Java2021_4_8;
import sun.util.resources.ms.CalendarData_ms_MY;
/**
* @Create with IntelliJ IDEA
* @Description :
* @Auther : HMW
* @Date: 2021-04-08
* @Time: 22:14
**/
public class test_thread {
static class MyThread extends Thread {
@Override
public void run() {
// super.run();
System.out.println("hello world, 我是一个线程");
}
}
static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("我是一个新线程33");
}
}
public static void main1(String[] args) {
//1、创建线程类 - 这个并不会在内存分配空间
MyThread myThread = new MyThread();
//下面的实例会让进程跑起来
myThread.start();
//2、通过匿名内部类继承方式创建
Thread thread1 = new Thread() {
@Override
public void run() {
System.out.println("我是一个新线程");
}
};
thread1.start();
//3、创建一个继承Runnable接口的类创建。
Thread thread2 = new Thread(new MyRunnable());
thread2.start();
//4、 Runnable匿名内部类
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("我是一个新线程444");
}
};
Thread thread3 = new Thread(runnable);
thread3.start();
//5、lamdba方法
Thread thread5 = new Thread(()-> {
System.out.println("我是一个新的线程555");
});
thread5.start();
}
public static void main2(String[] args) {
Thread thread = new Thread("郝梦武") {
@Override
public void run() {
//
int count = 10;
while(count >= 0) {
count--;
}
System.out.println("我即使gg");
}
};
System.out.println(thread.getName());
System.out.println(thread.getPriority());
System.out.println(thread.isDaemon());
System.out.println(thread.getId());
System.out.println(thread.getState());
thread.start();
}
static boolean isQuit = false;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread("郝梦武") {
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()) {
System.out.println("正在处理中...");
// try {
// Thread.sleep(500);
// }
// catch(InterruptedException e) {
// e.printStackTrace();
// System.out.println("Thread.slepp发生异常, 被捕获到");
// System.out.println(Thread.currentThread().isInterrupted());
// break;
/*
真的很神奇, 主线程中断子线程, 在没有异常捕捉, 中断状态会发生变化导致退出。
如果被异常捕捉到, 不会导致中断状态发生变化。
*/
// }
}
//交易中止
System.out.println("交易中断");
System.out.println(Thread.currentThread().getName());
}
};
thread.start();
Thread.sleep(5000);
System.out.println("请求交易中止");
thread.interrupt();
System.out.println("主动中止交易");
}
}
Java练习代码(五)- 线程
最新推荐文章于 2024-07-31 19:38:21 发布