Java Thread

线程(thread):比进程更小的运行单位,是程序中单个顺序的流控制

Java中自定义线程类的两种方式

1.继承Thread类,重写run();方法。

2.实现Runnable接口,实现run();方法。

package me.liangliang.thread;
class CustomerThread extends Thread {
public CustomerThread() {
super("CustomerThread");
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " start.");
for (int i = 0; i < 5; i++) {
System.out.println(threadName + " loop at " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(threadName + " end.");
}
}


class CustomerThread2 extends Thread {
CustomerThread customerThread;
public CustomerThread2(CustomerThread customerThread) {
super("CustomerThread2");
this.customerThread = customerThread;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " start.");
try {
customerThread.join();
System.out.println(threadName + " end.");
} catch (Exception e) {
e.printStackTrace();
}
}
}


public class TestJoinDemo {
public static void main(String[] args) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " start.");
CustomerThread customerThread = new CustomerThread();
CustomerThread2 customerThread2 = new CustomerThread2(customerThread);
try {
customerThread.start();
Thread.sleep(2000);
customerThread2.start();
customerThread2.join();  //挂起主线程,等customerThread2执行完后,再执行主线程
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadName + " end.");
}
}

执行结果可能为

main start.
CustomerThread start.
CustomerThread loop at 0
CustomerThread loop at 1
CustomerThread loop at 2
CustomerThread2 start.
CustomerThread loop at 3
CustomerThread loop at 4
CustomerThread end.
CustomerThread2 end.
main end.

注释掉customerThread2.join(); 后,执行结果可能为

main start.
CustomerThread start.
CustomerThread loop at 0
CustomerThread loop at 1
main end.
CustomerThread2 start.
CustomerThread loop at 2
CustomerThread loop at 3
CustomerThread loop at 4
CustomerThread end.
CustomerThread2 end.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值