JAVA线程的三种简单实现

JAVA并发编程的书有很多,对我胃口的就这一本:《Java并发编程从入门到精通》。


不厚,但从入门讲起。


今天实践了三种线程的简单实现。

b99511fd103cac74ce81df151390e21baf1519f9



ThreadA


package demo.thread;

public class ThreadA extends Thread {
	public void run() {
		super.run();
		try {
			Thread.sleep(500L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("This is thread A.");
	}

}


ThreadB


package demo.thread;

public class ThreadB implements Runnable {
	public void run() {
		try {
			Thread.sleep(600L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("This is thread B.");
	}

}


ThreadC


package demo.thread;

import java.util.concurrent.Callable;

public class ThreadC implements Callable<String> {
	public String call() throws Exception {
		try {
			Thread.sleep(500L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("This is thread C.");
		return "thread C";
	}

}


ThreadMain


package demo.thread;

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

public class ThreadMain {
	public static void main(String[] args) {
		ThreadA threadA = new ThreadA();
		threadA.start();
		
		ThreadB threadB = new ThreadB();
		new Thread(threadB).start();
		
		ThreadC threadC = new ThreadC();
		FutureTask<String> future = new FutureTask<String>(threadC);
		new Thread(future).start();
		
		System.out.println("This is main thread.");
		System.out.println("This is main thread begin.");
		
		try {
			System.out.println("threadC return value: " + future.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		
		System.out.println("This is main thread end.");
	}

}


输出样子

e4cd97ac5e7e28737dc3db4a1d4c56a0718805b6


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值