创建线程
src/step1/ThreadClassOne.java
package step1;
//请在此添加实现代码
/********** Begin **********/
public class ThreadClassOne extends Thread {
public void run() {
for(int i = 1;i<10;i++) {
System.out.print(i+" ");
i++;
}
}
}
class ThreadClassTwo extends Thread {
public void run() {
for(int i = 0;i<=10;i++) {
System.out.print(i+" ");
i++;
}
}
}
/********** End **********/
src/step1/ThreadClassTwo.java
package step1;
//请在此添加实现代码
/********** Begin **********/
public class ThreadClassTwo {
}
/********** End **********/
使用 Callable 和 Future 创建线程
src/step2/Task.java
package step2;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Task {
public void runThread(int num) {
//请在此添加实现代码
/********** Begin **********/
// 在这里开启线程 获取线程执行的结果
ThreadCallable tc = new ThreadCallable(num);
FutureTask<Integer> ft = new FutureTask<Integer>(tc);
new Thread(ft,"线程").start();
try {
System.out.println("线程的返回值为:"+ft.get());
} catch (Exception e) {
e.printStackTrace();
}
/********** End **********/
}
}
//请在此添加实现代码
/********** Begin **********/
/* 在这里实现Callable接口及方法 */
//第一种解题
class ThreadCallable implements Callable<Integer> {
private int num;
public ThreadCallable() {
}
public ThreadCallable(int num) {
this.num = num;
}
public Integer call() throws Exception {
int[] arr = new int[2];
arr[0] = 1;
arr[1] = 1;
for (int i = 2; i < num; i++) {
int tmp = arr[1];
arr[1] = arr[0] + arr[1];
arr[0] = tmp;
}
return arr[1];
}
}
//第二种解
// class ThreadCallable implements Callable<Integer> {
// private int num;
// public ThreadCallable() {
// }
// public ThreadCallable(int num) {
// this.num = num;
// }
// public Integer call() throws Exception {
// int p = 0;
// int a = 1;
// int sum = 1;
// for (int i = 1; i < num; i++) {
// sum = p + a;
// p = a;
// a = sum;
// }
// return sum;
// }
// }
/********** End **********/