三种实现方式
Thread:
class X extends Thread{}
X x1 = new X();
x1.start();
Runnable:
class Y implements Runnable{}
Runnable r1 = new Runnable();
Thread t1 = new Thread(r1);
t1.start();
callable:需要有一个返回值
//创建一个服务
TestCallable testCallable = new testCallable();
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交运行
Future r1 = ser.submit(testCallable1);
Future r2 = ser.submit(testCallable2);
Future r3 = ser.submit(testCallable3);
//获取结果
boolean rs1 = r1.get();
boolean rs2 = r2.get();
boolean rs3 = r3.get();
System.out.println(rs1);
System.out.println(rs2);
System.out.println(rs3);
//关闭服务
ser.shutdownNow();
龟兔赛跑
//龟兔赛跑
public class TestRace implements Runnable{
int length = 100;
int turtle = 0;
int rabbit = 0;
boolean GameOver = true;
@Override
public void run() {
while(GameOver){
//System.out.println("run");
if(Thread.currentThread().getName()=="turtle"){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (turtle == 100) {
System.out.println("GameOver!turtle wins!");
GameOver = false;
} else {
System.out.println(Thread.currentThread().getName() + " have run" + turtle++ + "meters");
}
}
if(Thread.currentThread().getName()=="rabbit") {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(rabbit == 80){
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (rabbit == 100) {
System.out.println("Game Over!rabbit wins!");
GameOver = false;
} else {
System.out.println(Thread.currentThread().getName() + " have run" + rabbit++ + "meters");
}
}
}
}
public static void main(String[] args) {
TestRace testRace = new TestRace();
new Thread(testRace,"turtle").start();
new Thread(testRace,"rabbit").start();
}
}
Lambda表达式
对于一个单抽象方法的接口(即函数式接口),可以用lambda来简化
interface A{
void X();
}
class B implements A{
public static void main(String[] args) {
@Override
public void X{
System.out.println();
}
}
A a = new B();
a.X();
}
可以改写为
A a = ()-> System.Out.println();