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;
}
}字节(Byte)是计量单位,表示数据量多少,是计算机信息技术用于计量存储容量的一种计量单位,通常情况下一字节等于八位。字符(Character)计算机中使用的字母、数字、字和符号,比如'A'、'B'、'$'、'&'等。一般在英文...
在java中字符串属于对象,刚开始我就疑惑为什么int char等类型都是小写,结果String是大写,java太反人类,后来才知道String是对象。(1).java创建字符串String text = "net"; String tex...
java stringBuffer(1).stringBuffer和stringBuilder区别stringBuffer是线程安全的,stringBuilder速度更快(2).简单的stringBuffer例子StringBuffer sBuffer = new&nb...
(1).java睡眠函数Thread.sleep(时间); //单位为毫秒(2).java睡眠函数例子Date dNow = new Date(); SimpleDateFormat ft = new&nbs...
System.out.println("当前时间戳(秒): " + System.currentTimeMillis()/1000); System.out.println("当前时间戳(毫秒): " +&nb...
pattern表示正则表达式,接收正则表达式作为参数例子:String content = "my name is gaojiufeng"; String pattern = "....