JavaThread、Runnable、Callable、线程池的使用

16 篇文章 1 订阅

目录

一、继承Thread类

二、实现Runnable接口

三、继承Callable接口

四、线程池


一、继承Thread类

public class TestThread1 extends Thread {
	
	@Override
	public void run() {
		for(int i=1; i<=100; i++) {
			System.out.println("线程1的" + i);
			try {
				sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}

public class TestThread2 extends Thread {

	@Override
	public void run() {
		for(int i=1; i<=100; i++) {
			System.out.println("线程2的:" + i);
			try {
				sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
public class Test {

	public static void main(String[] args) {
		
		TestThread1 thread1 = new TestThread1();
		TestThread2 thread2 = new TestThread2();		
		
		thread1.start();
		thread2.start();
	}
}

        因为打一次要睡100ms,所以是一个线程一次

二、实现Runnable接口

public class TestRunnable1 implements Runnable {

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

}
public class TestRunnable2 implements Runnable {

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

}
public class Test {
	
	public static void main(String[] args) {
		
		TestRunnable1 run1 = new TestRunnable1();
		TestRunnable2 run2 = new TestRunnable2();
		
		new Thread(run1).start();
		new Thread(run2).start();
	}
}

三、继承Callable接口

public class TestCallable1 implements Callable<Integer> {

	@Override
	public Integer call() throws Exception {

		for(int i=0; i<100; i++) {
			System.out.println("线程1: " + i);
		}
		return null;
	}


}
public class TestCallable2 implements Callable<Integer> {

	@Override
	public Integer call() throws Exception {

		for(int i=0; i<100; i++) {
			System.out.println("线程2: " + i);
		}
		return 0;
	}

}
public class Test {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		
		FutureTask<Integer> task1 = new FutureTask<>(new TestCallable1());
		FutureTask<Integer> task2 = new FutureTask<>(new TestCallable2());
		new Thread(task1).start();
		new Thread(task2).start();
		
		System.out.println("[线程返回数据]:  " + task1.get());
		System.out.println("[线程返回数据]:  " + task2.get());

	}
}

四、线程池

public class TestThreadPool {

	public static void main(String[] args) {
		ExecutorService e = Executors.newCachedThreadPool();
		
		e.execute(new Test1());
		e.execute(new Test2());
	}
}

class Test1 implements Runnable{

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

class Test2 implements Runnable{

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值