package com.ws;
public class Demo01 {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
for (int i = 0; i < 10; i++) {
System.out.println("主线程->"+i);
}
}
}
class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("分支线程->"+i);
}
}
}
2、实现Runnable接口,重写run方法(没有返回值)
package com.ws;
public class Demo02 {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
for (int i = 0; i < 1000; i++) {
System.out.println("主线程"+i);
}
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("分支线程"+i);
}
}
}
3、实现Callable接口重写call方法(有返回值)
package com.ws;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
/**
* 实现线程的第三种方式:
* 实现Callable接口
* 这种方式的优点:可以获取到线程的执行结果
* 这种方式的缺点:效率比较低,在获得t线程执行结果的时候,当前线程受阻塞,效率低。
*/
public class Demo03 {
public static void main(String[] args) throws Exception{
//第一步:创建一个”未来任务类“对象
FutureTask task = new FutureTask(new Callable() {
@Override
public Object call() throws Exception {//call()方法就相当于run方法
System.out.println("call method begin!!!");
Thread.sleep(10000);
System.out.println("call method end!!!");
int a = 100;
int b = 200;
return a + b;//自动装箱(300结果变成Integer)
}
});
//创建线程对象
Thread t = new Thread(task);
//启动线程
t.start();
//在这里是main方法
//在主线程中怎么获取t线程的返回值
Object o = task.get();
System.out.println("线程执行结果:"+o);
//main方法这里的程序要想执行必须等待get()方法的结束
//而get()方法可能需要很久,因为get()方法是为了拿到另一个线程的执行结果
//而另一个线程执行是需要时间的
System.out.println("Hello!!!");
}
}