传统线程技术和定时器的应用

创建线程的两种传统方式

代码
package thread;

public class TraditionalThread {
	public static void main(String[] args) {
		// 第一种 继承 Thread类
		Thread thread = new Thread() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("1 : " + Thread.currentThread().getName());
				}
			}
		};
		thread.start();

		// 第二种 Runnable接口 这种方式耦合度低, 并且更加符合面向对象的编程思想
		// 将线程 和线程所运行的代码分离 分别放到两个对象中 使用时在组合起来
		Thread thread2 = new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("2 : " + Thread.currentThread().getName());
				}
			}
		});
		thread2.start();

		new Thread(new Runnable() {
			@Override
			public void run() {
			}
		}) {
			public void run() {
				// 会运行这里的代码
				// 原因是子类对象重写了父类中的run方法,而寻找Runnable接口的run方法是在父类run方法重定义的
			};
		}.start();

	}
}

定时器程序

代码
package TraditionalThread;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TraditionalTimerTest {

	private static int count = 0;

	public static void main(String[] args) {
		// 炸弹 在程序启动后过3秒后爆炸 然后再每间隔1秒钟中爆炸一次
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				System.out.println("bombing!");
			}
		}, 3000, 1000);

		// 炸弹 在程序启动后过3秒后爆炸 然后再每间隔2,4,2,4...秒钟中爆炸一次
		class MyTimerTask extends TimerTask {
			@Override
			public void run() {
				count = (count + 1) % 2;
				System.out.println("bombing!");
				new Timer().schedule(new MyTimerTask(), 2000 + 2000 * count);
			}
		}
		new Timer().schedule(new MyTimerTask(), 3000);

		while (true) {
			try {
				Thread.sleep(1000);
				System.out.println(new Date().getSeconds());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值