Callable接口与Runable接口的区别:
(1).Callable规定的方法是call(),而Runnable规定的方法是run()
(2).Callable的任务执行后可返回值,而Runnable的任务是不能有返回值的
(3).call()方法可抛出异常,而run()方法是不能抛出异常的
(4).运行Callable任务可拿到一个Future对象
class Task implements Callable<Integer> {
public static void main(String[] args) throws OutOfMemoryError {
try {
execute();
} catch (Throwable e) {
System.out.println(e.getMessage());
}
}
/**
* execute
*
* @throws Exception
*/
public static void execute() throws Exception {
Task task = new Task();
// 线程1
Future<Integer> ft1 = new FutureTask<>(task);
new Thread((Runnable) ft1, "苦力1").start();
// 线程2
Future<Integer> ft2 = new FutureTask<>(task);
new Thread((Runnable) ft2, "苦力2").start();
// 获取线程1的最终执行返回值
System.out.println("苦力1最终的返回值是:" + ft1.get());
// 获取线程2的最终执行返回值
System.out.println("苦力2最终的返回值是:" + ft2.get());
}
@Override
public Integer call() throws Exception {
int i = 0;
int j = (new Random()).nextInt(5) + 5;
for (; i < j; i++) {
long threadId = Thread.currentThread().getId();
String threadName = Thread.currentThread().getName();
System.out.println("线程id:" + threadId + ",线程名称:" + threadName + ",正在循环,i等于" + i);
}
return i;
}
}public class test { public static void main(String[] args) { &...
public class test { public static void main(String[] args) { &...
java stringBuffer(1).stringBuffer和stringBuilder区别stringBuffer是线程安全的,stringBuilder速度更快(2).简单的stringBuffer例子StringBuffer sBuffer = new&nb...
(1).java获取当前日期时间Date date = new Date(); System.out.println(date.toString());输出Fri Jul 02 10:29:55 CST 2021(2).java获取时间戳秒/毫秒D...
System.out.println("当前时间戳(秒): " + System.currentTimeMillis()/1000); System.out.println("当前时间戳(毫秒): " +&nb...
pattern表示正则表达式,接收正则表达式作为参数例子:String content = "my name is gaojiufeng"; String pattern = "....