实现线程的三种方式及简单实例

什么是线程呢?

    是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点在运行中必不可少的资源,但它可与同属一个进程的其它线程共享进程所拥有的全部资源。一个线程可以创建和撤消另一个线程,同一进程中的多个线程之间可以并发执行。线程有就绪、阻塞和运行三种基本状态。

1、线程是轻量级的进程

2、线程没有独立的地址空间(内存空间)

3、线程是由进程创建的(寄生在进程)

4、一个进程可以拥有多个线程-->这就是我们常说的多线程编程

5、线程有几种状态:

  a、新建状态(new)

  b、就绪状态(Runnable)

  c、运行状态(Running)

  d、阻塞状态(Blocked)

  e、死亡状态(Dead)

线程的三种实现方式:

1.通过继承Thread类

public class Test1 {
	public static void main(String[] args) {
    //创建线程
	MyThread1 thread1=new MyThread1("线程1");
	MyThread1 thread2=new MyThread1("线程2");
	MyThread1 thread3=new MyThread1("线程3");
	//开启线程
	thread1.start();
	thread2.start();
	thread3.start();
	System.out.println("主线程");
	}
}
class MyThread1 extends Thread{
	String s;
	public MyThread1(String s) {
		this.s=s;
	}
	@Override
	public void run() {
		System.out.println(s);
	}
}

2.通过实现Runable接口实现

public class Test2 {
	
	public static void main(String[] args) {
		//创建真实线程对象
		MyThread2 thread1=new MyThread2("线程1");
		MyThread2 thread2=new MyThread2("线程2");
		MyThread2 thread3=new MyThread2("线程3");
		//创建代理线程对象,并引用真实对象
		Thread thread11=new Thread(thread1);
		Thread thread22=new Thread(thread2);
		Thread thread33=new Thread(thread3);
		//开启线程
		thread11.start();
		thread22.start();
		thread33.start();
		System.out.println("主线程");
	}
}
class MyThread2 implements Runnable{
    String s;
	public MyThread2(String s) {
		this.s=s;
	}
	@Override
	public void run() {
		System.out.println(s);
	}
	
}

3.通过实现Callable和调用Future异步实现

1)Callable接口


public class CallTest implements Callable<String>{

	String s;
	public CallTest(String s) {
		this.s=s;
	}
	//重写callable接口的call方法
	@Override
	public String call() throws Exception {
		System.out.println(s);
		return s;
	}

}

2)调用Future

public class Test3 {

	public static void main(String[] args) {
		//固定大小线程池
		ExecutorService executorService=Executors.newFixedThreadPool(3);
		List<CallTest> list=new ArrayList<>();
		list.add(new CallTest("线程1"));
		list.add(new CallTest("线程2"));
		list.add(new CallTest("线程3"));
		list.add(new CallTest("线程4"));
		list.add(new CallTest("线程5"));
		list.add(new CallTest("线程6"));
		try {
			//调用线程 ! 实现多线程,返回结果
			List<Future<String>> futures=executorService.invokeAll(list);
			
		} catch (InterruptedException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		System.out.println("主线程");
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值