【Java】三种方式创建多线程

通过集成Thread类实现多线程

package TreadLearning;

/**
 * 创建线程方法1
 * 利用继承Thread类+重写run方法
 * new对象然后调用start()方法(不能直接调用run方法)
 * @author 袁盛桐
 *
 */
public class TreadExtend extends Thread{

	@Override
	public void run() {
		for(int i=0; i<100; i++) {
			System.out.println("A"+i);
		}
	}
	
	public static void main(String[] args) {
		TreadExtend a = new TreadExtend();
		TreadExtend2 b = new TreadExtend2();
		a.start();
		b.start();
	}
}

class TreadExtend2 extends Thread{

	@Override
	public void run() {
		for(int i=0; i<100; i++) {
			System.out.println("B"+i);
		}
	}
	
	
}

重写runable接口创建多线程 

package TreadLearning;

/**
 * 创建线程方法2
 * 1.实现runnable接口+重写run方法
 * 2.启动多线程 使用静态代理
 *   (1)创建真实角色
 *   (2)创建代理角色+真实角色引用
 *   (3)调用start()来启动线程
 *   
 *好处(1)避免单继承的局限性
 * (2)便于共享资源
 * @author 袁盛桐
 *
 */
public class ThreadImpRunable implements Runnable{

	@Override
	public void run() {
		for(int i=0; i<100; i++) {
			System.out.println("A"+i);
		}
	}
	
	public static void main(String[] args) {
		//(1)创建真实角色
		ThreadImpRunable demo = new ThreadImpRunable();
		//(2)创建代理角色+真实角色引用
		Thread proxy = new Thread(demo);
		//(3)调用start()来启动线程
		proxy.start();//成为其中一条线程路径
		
		for(int i=0; i<100; i++) {
			System.out.println("B"+i);
		}
	}
}

重写callable接口创建多线程

package TreadLearning;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Call {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		//创建线程
		ExecutorService ser =Executors.newFixedThreadPool(1);
		ThreadImpCallable demo = new ThreadImpCallable();
		//获取值
		Future<Integer> result = ser.submit(demo);
		int num = result.get();
		System.out.println(num);
		//停止服务
		ser.shutdownNow();
	}
}

class ThreadImpCallable implements Callable<Integer>{
	
	@Override
	public Integer call() throws Exception {
		return 1000;
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值