多线程(Thread继承,Runnable接口,callable接口)

Thread继承

package java1;
class MyThread extends Thread{//线程的主体类
	private String title;
	public MyThread(String title) {
		this.title=title;
	}
	public void run() {
		for(int i=0;i<10;i++) {
			System.out.println(this.title+"运行"+i);
		}
	}

}
public class L1 {

	public static void main(String[] args) {
		new MyThread("线程A").start();
		new MyThread("线程B").start();
		new MyThread("线程C").start();
		
	}

}

Runnable接口(没有返回值)

package java1;
class MyThread implements Runnable{//线程的主体类
	private String title;
	public MyThread(String title) {
		this.title=title;
	}
	public void run() {
		for(int i=0;i<10;i++) {
			System.out.println(this.title+"运行"+i);
		}
	}

}
public class L1 {

	public static void main(String[] args) {
		Thread a=new Thread(new MyThread("线程A"));
		Thread b=new Thread(new MyThread("线程B"));
		Thread c=new Thread(new MyThread("线程C"));
		a.start();
		b.start();
		c.start();
		
	}

}

callable接口(有返回值)

package java1;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

class MyThread implements Callable<String>{//线程的主体类
	public String call() throws Exception{
		for(int i=0;i<10;i++) {
			System.out.println("线程执行"+i);
		}
		return "线程执行完毕";
	}
}
public class L1 {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		FutureTask<String> task =new FutureTask<>(new MyThread());
		new Thread(task).start();
		System.out.print("线程返回数据"+task.get());
		
	}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章