Luckylau's Blog

Java并发之线程工厂和异常处理

用线程工厂创建线程

ThreadFactory接口实现一个线程对象工厂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ThreadFactory;
public class MyTreadFactory implements ThreadFactory {
private int counter;
private String name;
private List<String> stats;
public MyTreadFactory(String name){
counter = 0;
stats = new ArrayList<String>();
this.name = name;
}
@Override
public Thread newThread(Runnable r) {
// TODO Auto-generated method stub
Thread t = new Thread(r, name+"_thread_"+counter);
counter++;
stats.add(String.format("Created thread %d with name %s on %s\n", t.getId(),t.getName(),new Date()));
return t;
}
public String getStats(){
StringBuffer sb = new StringBuffer();
Iterator<String> it = stats.iterator();
while(it.hasNext()){
sb.append(it.next());
sb.append("\n");
}
return sb.toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.concurrent.TimeUnit;
public class Task implements Runnable{
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Main {
public static void main(String[] args) {
MyTreadFactory factory = new MyTreadFactory("threadFactory");
Task task = new Task();
Thread thread;
System.out.println("Starting the Threads ");
for (int i = 0; i < 10; i++) {
thread = factory.newThread(task);
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Finish the Threads ");
System.out.println("Factory stats:");
System.out.printf("%s\n",factory.getStats());
}
}

在线程中处理不受控制的异常

在一个线程对象的run()方法里抛出一个检查异常,我们必须捕获并处理它们。因为run( )方法不接受throws子句。当一个非检查异常抛出,默认的的行为是在控制台写下stack trace并退出程序。

1
2
3
4
5
6
7
8
9
10
11
12
public class Task implements Runnable{
private int num =8;
private int res =0;
@Override
public void run() {
while(true){
res=12/num;
System.out.println("res: " +res );
num --;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
import java.lang.Thread.UncaughtExceptionHandler;
public class ExceptionHandler implements UncaughtExceptionHandler{
@Override
public void uncaughtException(Thread t, Throwable e) {
// TODO Auto-generated method stub
System.out.printf("An exception has been captured\n");
System.out.printf("Thread:%s\n",t.getId());
System.out.printf("Exception:%s :%s\n",e.getClass().getName(),e.getMessage());
System.out.printf("Stack Traace");
e.printStackTrace(System.out);
System.out.printf("Thread status:%s\n",t.getState());
}
}
1
2
3
4
5
6
7
8
public class Main {
public static void main(String[] args) {
Task task = new Task();
Thread thread = new Thread(task);
thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();
}
}
Luckylau wechat
如果对您有价值,看官可以打赏的!