java 创建线程的3种方式

1.继承Thread类
在这里插入图片描述在这里插入图片描述

  package com.thread;
    
    public class MyThread extends Thread {
    	private String name;
    
    	public MyThread(String name) {
    		this.name = name;
    	}
    
    	@Override
    	public void run() {
    		for (int i = 0; i < 15; i++) {
    			System.out.println(name + ":" + i);
    		}
    	}
    
    }


    package com.thread;
    public class TsetThread {
    
         public static void main(String[] args) {
        	  MyThread T1 = new MyThread("线程A");
              MyThread T2 = new MyThread("线程B");
              T1.start();
              T2.start();
    	}
    }

在这里插入图片描述
2.实现Runnable接口

package com.runnable;

public class MyThread implements Runnable{
	private int ticket = 10;   //资源
	
	@Override
	  //记得要资源公共,要在run方法之前加上synchronized关键字,要不然会出现抢资源的情况
    public synchronized  void  run() {
        for (int i = 0; i <10; i++) {
            if (this.ticket>0) {
                System.out.println("卖票:ticket"+this.ticket--);
            }
        }
        
    }

}


package com.runnable;
public class TsetRunnable {

     public static void main(String[] args) {
         MyThread t1 = new MyThread();
         new Thread(t1).start();//同一个t1,如果在Thread中就不行,会报错
         new Thread(t1).start();
         new Thread(t1).start();
	}
}

3.实现Callable接口

package com.callable;

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

 class MyThread implements Callable<String>{

	@Override
	public String call() throws Exception {
		for (int i = 0; i <10; i++) {
			System.out.println("线程执行 X" +i);
		}
		return "线程执行完毕";
	}
	
	
	public static class Test{
		public static void main(String[] args) throws InterruptedException, ExecutionException {
			FutureTask<String> task = new FutureTask<>(new MyThread());
			new Thread(task).start();
			System.out.println("==================线程返回数据=============="+task.get());
		}
	}
}

--------------------------------------三种创建线程方法对比--------------------------------------

实现Runnable和实现Callable接口的方式基本相同,不过是后者执行call()方法有返回值,后者线程执行体run()方法无返回值,因此可以把这两种方式归为一种这种方式与继承Thread类的方法之间的差别如下:

1、线程只是实现Runnable或实现Callable接口,还可以继承其他类。

2、这种方式下,多个线程可以共享一个target对象,非常适合多线程处理同一份资源的情形。

3、但是编程稍微复杂,如果需要访问当前线程,必须调用Thread.currentThread()方法。

4、继承Thread类的线程类不能再继承其他父类(Java单继承决定)。

注:一般推荐采用实现接口的方式来创建多线程

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值