java创建多线程的三种方式

1.多线程 继承Thread 实现Rnunable 和使用ExecutorService、Callable、Future 前两种大部分人学习的时候一定学过 第三种

1.继承 Thread
public class MyThread extends Thread {
@Override
public void run() {
int i=0;
while(true){
try {
sleep(100);
System.out.println(“我是”+getName()+"—"+i++);
} catch (InterruptedException e) {
e.printStackTrace();
}

        if(i>100){
            break;
        }
    }
}

}
调用
public class mains {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.setName(“线程1”);
MyThread myThread1 = new MyThread();
myThread1.setName(“线程2”);
myThread.start();
myThread1.start();
}

}
2.实现Runnable接口
public class MyThread implements Runnable {

private String name=null;

MyThread(String name){
    this.name=name;
}
String getName(){
    return name;
}

@Override
public void run() {
    int i=0;
    while(true){
        try {
           Thread.sleep(100);
            System.out.println("我是"+getName()+"---"+i++);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if(i>100){
            break;
        }
    }
}

}
调用
public class mains {
public static void main(String[] args) {
MyThread myThread = new MyThread(“线程1”);
MyThread myThread1 = new MyThread(“线程2”);
new Thread(myThread).start();
new Thread(myThread1).start();

}

}
其中还可以使用匿名类的方式
public class mains {
public static void main(String[] args) {
new Thread(new Runnable(){
public void run(){
int i=0;
while(true){
try {
Thread.sleep(100);
System.out.println(“我是”+i++);
} catch (InterruptedException e) {
e.printStackTrace();
}

              if(i>100){
                  break;
              }
          }
       }
   }).start();

}

}
lambda表达式的方式
public class mains {
public static void main(String[] args) {
new Thread(()->{
int i=0;
while(true){
try {
Thread.sleep(100);
System.out.println(“我是”+i++);
} catch (InterruptedException e) {
e.printStackTrace();
}

          if(i>100){
              break;
          }
      }
  }).start();

}

}
3.线程池创建带返回值的线程
public class mains {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(5);//线程池大小为5i
List array=new ArrayList();
for(int i=0; i<5; i++){
Callable c = new MyCallable(“线程”+i);
Future submit = executorService.submit©;
array.add(submit);
}
for (Object fut:array) {
Future fut1 = (Future) fut;
Object o = fut1.get();
System.out.println(o);
}

}

}
class MyCallable implements Callable{
private String name;
MyCallable(String name){
this.name=name;
}

@Override
public Object call() throws Exception {
    int i=0;
    while(true){
        i++;
       Thread.sleep(100);
        if(i>100)break;
        System.out.println(this.name+"-"+i);
    }
   return this.name+"-"+i;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值