3种启动线程的方式
2019-04-08 本文已影响0人
Theodore的技术站
1.继承 thread 类
继承 thread 类,并重写 run 方法
public void MyThread extends Thread{
private int i;
@Override
public void run(){
for (; i < 10;i++)
{
System.out.println(getName() + "\t" + i);
}
}
}
测试:
public class MyTest{
public static void main(String[] args){
for (int i = 0;i < 10;i++){
System.out.println(Thread.currentThread.getName() + "\t" + i);
if (i == 5){
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.strat();
}
}
}
}
2.实现 Runnable 接口
public class MyRunThread implements Runnable{
private int i;
public void run(){
for (;i < 20; i++){
System.out.println(Thread.currentThread().getName()+" "+i);
if(i==20)
{
System.out.println(Thread.currentThread().getName()+"执行完毕");
}
}
}
}
测试:
public class MyTest{
public static void main(String[] args){
for (int i = 0;i < 10;i++){
System.out.println(Thread.currentThread.getName() + "\t" + i);
if (i == 5){
MyRunThread myThread = new MyThread();
Thread t1 = new Thread(myThread,"1");
Thread t2 = new Thread(myThread,"2");
t1.start();
t2.strat();
}
}
}
}
3.实现 Callable 接口
public class MyCallThread implements Callable<Integer>{
private int i;
public Integer call() throw Exception{
for (;i < 20;i++){
System.out.println(Thread.currentThread().getName()+""+i);
}
return i;
}
}
测试:
public class MyTest{
public static void main(String[] args){
MyCallThread t1 = new MyCallThread();
FutureTask<Integer> f = new FutureTask<>(t1);
Thread t2 = new Thread(f,"新线程");
t2.start();
try{
System.out.println(f.get());
}catch(Exception e) {
// TODO: handle exception
}
}
}