新增多线程示例

This commit is contained in:
fanxb 2019-04-09 11:18:22 +08:00
parent 6d475fff59
commit 6e43f898c0
6 changed files with 92 additions and 1 deletions

3
.gitignore vendored
View File

@ -49,4 +49,5 @@ hs_err_pid*
target
.mvn
mvnw
mvnw.cmd
mvnw.cmd
out

View File

@ -0,0 +1,2 @@
本文件用于说明包用途:
- base: 创建线程的两种方式

View File

@ -0,0 +1,8 @@
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
System.out.println("当前线程名为:"+Thread.currentThread().getName());
System.out.println("当前线程id为"+Thread.currentThread().getId());
}
}

View File

@ -0,0 +1,24 @@
package base;
/**
* 类功能简述
* 类功能详述
*
* @author fanxb
* @date 2019/4/9 10:54
*/
public class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("捕获到线程"+t.getName()+",异常:" + e.getMessage());
e.printStackTrace();
}
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler());
new Thread(() -> {
throw new RuntimeException("test");
}).start();
}
}

View File

@ -0,0 +1,25 @@
package base;
/**
* 类功能简述
* 类功能详述
*
* @author fanxb
* @date 2019/4/8 11:04
*/
public class CustomThreadExtendThread extends Thread{
@Override
public void run() {
String threadName = Thread.currentThread().getName();
long threadId = Thread.currentThread().getId();
System.out.println("创建线程名为:"+threadName+",id为"+threadId);
}
public static void main(String[] args){
Thread thread1 = new CustomThreadExtendThread();
Thread thread2 = new CustomThreadExtendThread();
thread1.start();
thread2.start();
}
}

View File

@ -0,0 +1,31 @@
package base;
/**
* 类功能简述
* 类功能详述
*
* @author fanxb
* @date 2019/4/8 11:11
*/
public class CustomThreadImplementInterface implements Runnable {
@Override
public void run() {
Thread.currentThread().setName(((Double) Math.random()).toString());
String threadName = Thread.currentThread().getName();
long threadId = Thread.currentThread().getId();
System.out.println("创建线程名为:" + threadName + ",id为" + threadId);
}
public static void main(String[] args) {
Thread thread1 = new Thread(new CustomThreadImplementInterface());
Thread thread2 = new Thread(new CustomThreadExtendThread());
thread1.start();
thread2.start();
//使用lambda表达式让创建线程更简单
new Thread(() -> {
System.out.println("创建了一个新线程");
}).start();
}
}