多线程-创建线程的三种方式

一.通过继承Thread类实现

1.子类SubThread继承Thread

2.重写run()方法:子线程的执行体

3.创建子类SubThread,并调用start():启动线程

public class subThread1 extends Thread{
		
		public subThread1(){
				System.out.println("构造函数");
			}
		int i = 0;
		// 重写run() 方法
		public void run(){
				for(; i < 100; i++){
						System.out.println(Thread.currentThread().getName() + " : " + i);
					}	
			}
		
		public static void main(String[] args){
				for(int j = 101; j < 150; j++){
					System.out.println(Thread.currentThread().getName() + " : " + j);
					
					if(120 == j){
							// 创建2个子线程,并执行
							new subThread1().start();
							new subThread1().start();
						
						}
					
					}
			
			}
	
	}


二.通过实现Runnable接口

1.创建实现Runnable接口的实现类

2.定义run()方法:子线程执行体

3.将实现类对象作为target传给Thread类, Thead对象调用start()启动线程

public class subThread2 implements Runnable{
		
		int i = 0;
		public void run(){
				for(; i < 100; i++){
						System.out.println(Thread.currentThread().getName() + " " + i);
					}
		
			} 
	
		public static void main(String[] args){
				
				subThread2 st2 = new subThread2();
				
				for(int j = 101; j < 150; j++){
						System.out.println(Thread.currentThread().getName() + " " + j);
					
					
						if(120 == j){
								// Runnable实现类的对象作为Thread的target创建Thread对象, sub1指定线程名
								new Thread(st2, "sub1").start();
								new Thread(st2, "sub2").start();
					}
				}
			}
	}

三.实现Callable接口

1.定义Callable接口的实现类,并实现call()方法:子线程的执行体, 该方法可以有返回值,并可以抛出异常

2.创建实现类的实例,作为FutureTask类实例的target

3.将FutureTask类实例作为Thread类实例的target, 调用start():执行子线程

4.调用FutureTask类实例的get()方法获取子线程执行(call())的返回值

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

// Callable必须指定泛型
public class subThread3 implements Callable<Integer>{
	
		int i = 0;
		// 子线程的执行体, 可以有返回值, 并能抛异常,  返回类型必须与Callable定义的泛型一致
		public Integer call(){
				for(; i < 100;  i++){
						System.out.println(Thread.currentThread().getName() + " " + i);
					}
					
				return i;
			}
			
		public static void main(String[] args){
				
				subThread3 st3 = new subThread3();
				// Future接口(Callable接口call方法的返回值)的实现类,FutureTask并实现了Runnable接口, 可作为Thread的Target
				// get()为call()方法的返回值
				FutureTask<Integer> ft = new FutureTask<Integer>(st3);
				for(int j=101; j < 150; j++){
						System.out.println(Thread.currentThread().getName() + " " + j);
					
					
						if(120 == j){
							// 作为Thread的Target, start()执行线程
							new Thread(ft).start();
							
						}
				}
				try{
					System.out.println("子线程执行后,i的值: " + ft.get());
				}catch(Exception e){
					 e.printStackTrace();
					}
					
		}
				
	
	
	}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值