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;
}
}