Java Thread

来源:互联网 发布:阿里云服务器老被攻击 编辑:程序博客网 时间:2024/05/22 09:03

线程(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.

0 0
原创粉丝点击