JAVA中实现多线程有几种种方式,一种是集成Thread类,一种是实现Runnable接口。
但还有另外一种方式就是实现 concurrent的Collable接口,该接口和Runnable接口相似,区别就是Runnable不会有返回结果,并且不能抛出运行时异常,但是Callable可以。
Thread和Callable不适合资源共享,而实现Runnable接口的类可以资源共享。
例如继承Extends的类如下:
public class ThreadExtend extends Thread {
private int ticket = 5; //5张票
public void run() {
for (int i=0; i<=20; i++) {
if (this.ticket > 0) {
System.out.println(Thread.currentThread().getName()+ "正在卖票"+this.ticket--);
}
}
}
public static void main(String[] args) {
Thread h1 = new ThreadExtend();
Thread h2 = new ThreadExtend();
Thread h3 = new ThreadExtend();
h1.start();
h2.start();
h3.start();
}
}
实现了Runnable接口的类代码如下:
public class ThreadExtend extends Thread {
private int ticket = 2; //5张票
public void run() {
for (int i=0; i<=20; i++) {
if (this.ticket > 0) {
System.out.println(Thread.currentThread().getName()+ "正在卖票"+this.ticket--);
}
}
}
public static void main(String[] args) {
Thread h1 = new ThreadExtend();
Thread h2 = new ThreadExtend();
Thread h3 = new ThreadExtend();
h1.start();
h2.start();
h3.start();
}
}
实现了Callable接口的类代码如下:
class CThread implements Callable<String>{
private int ticket = 2; //5张票
public String call() {
for (int i=0; i<=20; i++) {
if (this.ticket > 0) {
System.out.println(Thread.currentThread().getName()+ "正在卖票"+this.ticket--);
}
}
return "success";
}
}
public class CallableImplement {
public static void main(String [] args) {
ExecutorService service = Executors.newFixedThreadPool(5);
List<Callable<String>>jobs=new ArrayList<Callable<String>>();
jobs.add(new CThread());
jobs.add(new CThread());
jobs.add(new CThread());
try {
List<Future<String>> dwJobThreads = service.invokeAll(jobs);
for(Future<String> future:dwJobThreads){
System.out.println(future.get());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1万+

被折叠的 条评论
为什么被折叠?



