创建多线程的有三种方式
一 继承Thread 重写run 方法
class Test01{
public static void main(String[] args) {
myTh myTh = new myTh();
myTh.start();
}
}
//1 继承 Thread 重写 run 方法
class myTh extends Thread{
@Override
public void run() {
//获取线程名
System.out.println(Thread.currentThread().getName()+"执行了");
try {
//延迟100 毫秒
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
实现 runnable 接口
class Test01{
public static void main(String[] args) {
long f = System.currentTimeMillis();
//-------------------------------------------------------
RTh rth = new RTh();
new Thread(rth).start();
//-------------------------------------------------------
long h = System.currentTimeMillis();
System.out.println(h-f);
}
}
//2 实现 runnable 接口
class RTh implements Runnable{
@Override
public void run() {
//获取线程名
System.out.println(Thread.currentThread().getName()+"执行了");
try {
//延迟100 毫秒
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
实现callable接口 创建带有返回值的线程
class Test01{
public static void main(String[] args) throws ExecutionException, InterruptedException {
long f = System.currentTimeMillis();
//-------------------------------------------------------
Cth cth = new Cth();
FutureTask<String> tsk = new FutureTask<String>(cth);
FutureTask<String> tsk2 = new FutureTask<String>(cth);
//新建一个线程运行
new Thread(tsk).start();
new Thread(tsk2).start();
System.out.println(tsk.get()); //等待返回 未返回 会阻塞 主线程 之后才会继续执行
System.out.println("11111");
System.out.println(tsk2.get());
//-------------------------------------------------------
long h = System.currentTimeMillis();
System.out.println(h-f);
}
}
//3 实现callable 接口 形成带有返回值的线程
class Cth implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+"执行了");
return "我执行完了";
}
}
注意: 如果 fultertask 在主线中使用 总耗时取决于耗费时间最长的线程 将会阻塞主线程