博主前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住也分享一下给大家
👉点击跳转到教程
常用方法:
注意细节大家可以看一下:
下面通过代码的方式,来使用上面所说的方法:
public class ThreadMethod1 {
public static void main(String[] args) {
//测试相关的方法
T t = new T();
//设置线程名称
t.setName("筱路");
//设置线程优先级 ,这里设置最小优先级为1
t.setPriority(Thread.MIN_PRIORITY);
t.start(); //启动子线程
//主线程打印5 hi 之后就中断子线程的休眠
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
System.out.println("hi" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(t.getName() + "线程的优先级=" + t.getPriority());
//中断子线程的休眠
t.interrupt();
}
}
class T extends Thread { //自定义线程类
@Override
public void run() {
while (true) {
for (int i = 0; i < 10; i++) {
//Thread.currentThread().getName() 获取当前线程的名称
System.out.println(Thread.currentThread().getName() + "在学习~~~" + i);
}
try {
System.out.println(Thread.currentThread().getName() + "休眠中~~~");
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
//当线程执行到一个interrupt方法时,就会catch一个异常,可以加入自己的业务代码
//InterruptedException 是捕获到一个中断异常
System.out.println(Thread.currentThread().getName() + "被 interrupt了");
}
}
}
}
还有两个方法,一个是join()和yield()方法
下面通过代码来体会一下,这两个方法的使用:
public class ThreadMethod2 {
public static void main(String[] args) {
T2 t2 = new T2();
t2.start();
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程吃了(小弟)" + i + "包子");
if (i == 5) {
System.out.println("主线程(小弟)让子线程(老大)先吃");
try {
// t2.join(); //这里相当于让t2线程先执行完毕
Thread.yield(); //礼让,不一定成功
System.out.println("子线程(老大)吃完了,主线程(小弟)继续吃");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
class T2 extends Thread { //自定义线程类
@Override
public void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("子线程吃了" + i + "包子");
}
}
}
守护线程,通过给线程setDaemon(true),将该线程设置为守护线程。
通过下面的代码来体会守护线程,注释已经在代码中给出
public class ThreadMethod3 {
public static void main(String[] args) {
MyDaemonThread myDaemonThread = new MyDaemonThread();
//如果我们希望当main线程结束后,子线程自动结束
//只需将子线程设为守护线程即可
myDaemonThread.setDaemon(true);
myDaemonThread.start();
for (int i = 1; i <= 10; i++) {
System.out.println("我在敲代码");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyDaemonThread extends Thread {
@Override
public void run() {
for (; ; ) { //无限循环
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("娱乐时间");
}
}
}
运行结果,正常情况下子线程会无限执行,但是该子线程被设置为了守护线程,主线程结束了,子线程也就跟着结束了。
以上就是java线程中常用方法的介绍,继续努力,冲冲冲~