Java多线程(二):线程的常用方法

线程常用方法——join()、sleep()、interrupt()、setPriority()

1、join()方法

让调用该方法的线程先执行完毕,而其他线程都处于阻塞状态,直到调用该方法的线程死亡。

源码:

public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

测试代码:

public class JoinThreadDemo {

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		ThreadJoin threadJoin1 = new ThreadJoin();
		ThreadJoin threadJoin2 = new ThreadJoin();
		threadJoin1.start();
		threadJoin1.join(); // 让threadJoin1线程先执行完,其他线程都处于等待状态

		threadJoin2.start();
		threadJoin2.join();// 让threadJoin2线程先执行完,其他线程都处于等待状态

		// 保证主线程永远都能在最后执行完毕
		for (int i = 0; i < 30; i++) {
			System.out.println("main...---" + i);
		}
	}

}

class ThreadJoin extends Thread {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < 30; i++) {
			System.out.println(getName() + "---" + i);
		}
	}
}

2、sleep()方法

sleep()是Thread类中的静态方法,需要通过Thread类调用,同时sleep方法会影响程序的运行时间(多了休眠时间)

测试代码:

public class SleepThreadDemo {

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub

		long startTime = System.currentTimeMillis();

		SleepThread sleepThread = new SleepThread();
		sleepThread.start();
		Thread.sleep(1000);
		long endTime = System.currentTimeMillis();

		System.out.println("程序运行时间: " + (endTime - startTime) + "ms");
	}

}

class SleepThread extends Thread {
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < 10000; i++) {
			// do nothing
		}
	}
}

 

3、interrupt()方法

  • interrupt(),在一个线程中调用另一个线程的interrupt()方法,中断状态(interrupted status) 会被置位,从而中断该线程。但线程的中断不意味着线程的停止
  • isInterrupted(),用来判断当前线程的中断状态(返回boolean类型的interrupted status)
  • interrupted() 是Thread的静态方法,测试的是当前线程(current thread)的中断状态,且这个方法会清除中断状态

注:interrupted()方法时不能中断被锁住的线程的,如synchronized实现同步锁的线程,是无法响应中断的;Lock锁能通过lockInterruptibly()方法让等待锁的线程响应中断。详情请看 Java多线程(三):线程安全问题(下)Lock

停止线程的stop()方法已经过时

测试代码:

public class StopThreadDemo {
	public static void main(String[] args) {
		StopThread stopThread1 = new StopThread();
		StopThread stopThread2 = new StopThread();
		stopThread1.start();
		stopThread2.start();
		for (int i = 1; i < 30; i++) {
			try {
				Thread.sleep(10);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			System.out.println("这里第" + i + "次线程运行-----:");
			if (i == 20) {
				stopThread1.interrupt(); // 中断线程
				stopThread2.interrupt(); // 中断线程
			}
		}
	}
}

class StopThread extends Thread {
	// flag为true 线程处于运行状态
	// flag为false 线程停止
	private boolean flag = true;

	@Override
	public synchronized void run() {
		while (flag) {
			try {
				wait();
			} catch (Exception e) {
				// TODO: handle exception
				stopThread(); // 修改运行标记
			}
			System.out.println(Thread.currentThread().getName() + "--- 这是子线程");

		}
	}
	// 由于中断方法不会停止线程,所以加一个线程停止的方法
	public void stopThread() { // 改变线程运行标记
		flag = false;
	}
}

 

4、setPriority()方法

设置线程的优先级

1 . 优先级表示重要程度或者紧急程度.但是能不能抢到资源也是不一定. 
2 . 分配优先级:反映线程的重要或紧急程度 
线程的优先级用1~10 表示,1的优先级最低,10的优先级最高,默认值是5

测试代码:

public class SetPriorityThreadDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		ThreadTest t1 = new ThreadTest();
		for (int i = 0; i < 40; i++) {
			System.out.println(Thread.currentThread().getName() + "---" + i);
			if (i == 19) {
				// 给子线程附最大优先级
				t1.setPriority(Thread.MAX_PRIORITY);
				System.out.println("线程最大优先级为:" + Thread.MAX_PRIORITY);
				// 使子线程处于就绪状态,看是否能抢占正在运行状态的主线程
				t1.start();
			}
		}
	}
}

class ThreadTest extends Thread {
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < 5; i++) {
			System.out.println(Thread.currentThread().getName() + "---" + i);
		}
	}
}

 


笔者水平有限,若有错误欢迎纠正,希望获得大家的建议

参考:https://www.cnblogs.com/lwbqqyumidi/p/3817517.html

           https://www.cnblogs.com/zeroingToOne/p/9063116.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值