线程并发库(创建线程、守护线程、暂停线程)

开启线程第一种方式:

public class test {
	public static void main(String[] args) {
		Thread t1 = new MyThread();
		t1.start(); // 开线程
		for (int i = 0; i < 100; i++)
			System.out.println(Thread.currentThread().getName() + ": B: " + i);
	}
}
class MyThread extends Thread {
	public void run() {
		for (int i = 0; i < 100; i++)
			System.out.println(Thread.currentThread().getName() + ": A: " + i);
	}
}
开启线程第二种方式:

public class test {
	public static void main(String[] args) {
		Thread t2 = new Thread(new MyRunnable());
		t2.start(); // 开线程
		for (int i = 0; i < 100; i++)
			System.out.println(Thread.currentThread().getName() + ": B: " + i);
	}
}
class MyRunnable implements Runnable {
	public void run() {
		for (int i = 0; i < 100; i++)
			System.out.println(Thread.currentThread().getName() + ": A: " + i);
	}
}
使用匿名内部类创建子线程:

		new Thread("线程3") {	
			public void run() {
				for (int i = 0; i < 100; i++)
					System.out.println(Thread.currentThread().getName() + ": C: " + i);
			}
		}.start();

		new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 100; i++)
					System.out.println(Thread.currentThread().getName() + ": D: " + i);
			}
		}, "线程4").start();
守护线程:

		final Thread t1 = new Thread() {
			public void run() {
				for (int i = 0; i < 5; i++) {
					System.out.println(Thread.currentThread().getName() + ": " + i);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		
		Thread t2 = new Thread() {
			public void run() {
				for (int i = 0; i < 10; i++) {
					System.out.println(Thread.currentThread().getName() + ": " + i);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		t2.setDaemon(true);		// 设置为守护线程, 不单独运行
		t1.start();		// 5次, 5秒就结束了
		t2.start();		// 10次, 需要10秒
		
		// 程序在所有非守护线程执行结束之后才结束
当前线程暂停,等待加入的线程运行结束之后再继续:

		final Thread t1 = new Thread() {
			public void run() {
				for (int i = 0; i < 5; i++) {
					System.out.println(Thread.currentThread().getName() + ": " + i);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		
		Thread t2 = new Thread() {
			public void run() {
				for (int i = 0; i < 10; i++) {
					System.out.println(Thread.currentThread().getName() + ": " + i);
					try {
						Thread.sleep(1000);
						if(i == 1)
							t1.join();		// 当前线程暂停, 等待t1运行结束之后再继续
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
			
		t1.start();		// 5次, 5秒就结束了
		t2.start();		// 10次, 需要10秒




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

傅荣康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值