Java——关于多线程的记录(待补充)

一、多线程的实现

1.继承Thread类实现多线程

定义一个类继承Thread类,并覆写public void run()方法,多线程要实现的功能都在run方法中定义,要注意run方法不能被直接调用,而应该通过start()方法来执行多线程启动。每一个线程对象只能启动一次,不能重复启动。

class MyThread extends Thread{
	@Override
	public void run(){
		for(int x = 0;x<10;x++){
			System.out.println("x的值为:"+x);
		}
	}
}

public class ThreadDemo {
	public static void main(String args[]){
		MyThread mt = new MyThread();
		mt.start();
	}
}

2.实现Runnable接口来实现多线程

(1)实现Runnable接口,并覆写public void run()方法

(2)Thread类是Runnable的子类,Runnable接口没有start()方法启动多线程,但是可以通过Thread类的构造方法来实现:public Thread(Runnable target)

(3)为了避免Java单继承的局限性,优先考虑Runnable接口实现,通过Thread类对象启动多线程。

class MyThread implements Runnable{
	@Override
	public void run(){
		for(int x = 0;x < 10;x++){
			System.out.println("线程对象:"+x);
		}
	}
}

public class RunnableDemo {
	public static void main(String args[]){
		Thread thA = new Thread(new MyThread());
		Thread thB = new Thread(new MyThread());
		Thread thC = new Thread(new MyThread());
		thA.start();
		thB.start();
		thC.start();
	}
}

3.实现Callable接口实现多线程

(1)Callable接口与Runnable接口没有实质性的关系,但是Callable接口通过FutureTask这个类与Thread类产生关联,所以如果需要启动线程,必须通过FutureTask进行类对象的封装;

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

class MyThread implements Callable<String>{
	public String call(){
		for(int x = 0;x < 5;x++){
			System.out.println("x的值为:"+x);
		}
		return "线程执行完毕";
	}
}

public class RunnableDemo {
	public static void main(String args[]){
		FutureTask<String> mt = new FutureTask<String>(new MyThread());
		new Thread(mt).start();
	}
}

(2)Runnable接口是在JDK1.0的时候提出的,而Callable是在JDK1.5之后提出的;

(3)Java.lang.Runable接口中中只提供一个run()方法,并且没有返回值,而Java.util.concurrent.Callable中提供call()方法,并且有返回值

总结:这三种实现多线程的方法都需要Thread类对象调用start()方法来启动线程。


发布了12 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_41552756/article/details/103275234
今日推荐