Java 多线程进阶笔记
线程启动
- 第三种可以获得结果
- 继承Thread类, 不能继承其他类.
- Runable接口, 扩展性强.
第一种方式
package com.learn2.A10DuoXianCheng;
public class Mythread extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName()+"hello world");
}
}
}
Mythread t1 = new Mythread();
t1.setName("t1");
t1.start();
第二种方式
package com.learn2.A10DuoXianCheng;
public class T2Myrun implements Runnable {
@Override
public void run() {
Thread t = Thread.currentThread();
for (int i = 0; i < 100; i++) {
System.out.println(t.getName()+"hello world");
}
}
}
T2Myrun myrun = new T2Myrun();
Thread t1 = new Thread(myrun);
t1.setName("t1");
第三种方式
package com.learn2.A10DuoXianCheng;
import java.util.concurrent.Callable;
//泛型是结果的类型.
public class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum+=i;
}
return sum;
}
}
//创建Mycallable 继承 Callable接口, 实现 call方法有返回值
//创建Mycallable对象, 创建FutureTask对象(管理多线程执行结果的)
//创建thread对象,启动
MyCallable mc = new MyCallable();
FutureTask<Integer> ft = new FutureTask<>(mc);
Thread t1 = new Thread(ft);
t1.start();
System.out.println(ft.get());
成员方法
