java中创建线程的三种方式 线程五种状态之间的相互转换

第一种:

继承Thread类实现多线程

直接继承Thread类,并且覆写其中的run()方法(相当于主类中的main()方法)

此处每一个线程对象只能启动一次否则会抛出异常(RunTimeException)。

继承Thread类实现多线程会有单继承局限。

class MyThread extends Thread{
	private String title;
	public MyThread(String title) {
		super();
		this.title = title;
	}
	public void run () {
		for(int i=0;i<10;i++) {
			System.out.println(this.title+" "+Thread.currentThread().getName()+"、i :"+i);
		}
	}
		
	
}
public class Test2 {
	public static void main(String[] args) {
		MyThread myThread=new MyThread("微风");
		Thread thread=new Thread(myThread,"线程1");
		Thread thread2=new Thread(myThread,"线程2");
		thread.start();
		thread2.start();
	}

}

第二种:

Runnable接口实现多线程。

此时MyThread类实现了Runnable接口,但是继承的不再是Thread类,虽然解决了Thread的单继承局限问题,但是没有start()方法被继承,此时需注意,Thread类中提供了一个构造方法,public Thread(Runnable target),可以接受Runnable的接口对象,

class MyThread implements Runnable{
	private String title;
	public MyThread(String title) {
		super();
		this.title = title;
	}
	public void run () {
		for(int i=0;i<10;i++) {
			System.out.println(this.title+" "+Thread.currentThread().getName()+"、i :"+i);
		}
	}
		
	
}
public class Test2 {
	public static void main(String[] args) {
		MyThread myThread=new MyThread("微风");
		Thread thread=new Thread(myThread,"线程1");
		Thread thread2=new Thread(myThread,"线程2");
		thread.start();
		thread2.start();

使用匿名内部类进行Runnable创建

public class Test2 {
	public static void main(String[] args) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("HelloWorld");
				
			}
		}).start();
	}

}

使用lamda表达式进行Runnable对象创建

public class Test2 {
	public static void main(String[] args) {
		Runnable runnable=() -> System.out.println("helloworld");
		Thread thread=new Thread(runnable);
		thread.start();
	}

}

继承 Thread与实现Runnable区别

a.实现Runnable可以避免单继承局限

b.使用Runnable接口来实现多线程而已更好的体现出程序共享的概念

第三种:Callable实现多线程

不管何种情况,想要启动多线程只有Thread类中Start()方法

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

class MyThread implements Callable<String>{
	private int ticket=10;
	public String call() {
		while(ticket>0) {
			System.out.println("剩余票数"+this.ticket--);
		}
		return "票卖完了";
	}
	
}
public class Test2 {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		FutureTask<String> task=new FutureTask<>(new MyThread());
		new Thread(task,"黄牛A").start();
		new Thread(task,"黄牛B").start();
		System.out.println(task.get());
	}

}

线程五种状态间的相互转换

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值