多线程:线程的状态

 线程的方法:

 停止线程:

1.建议线程正常停止——>利用次数,不建议死循环

2、建议使用标志位——>设置一个标志位

3、不要使用stop或者destroy等过时或者JDK不建议使用的方法

线程的停止代码实现

public class Test implements Runnable{
	private boolean flag=true;
	public static void main(String[] args)  {
		Test test=new Test();
		new Thread(test).start();
		
		for (int i = 0; i < 1000; i++) {
			System.out.println("main"+i);
			if(i==900) {
				//调用stop方法切换flag的值,让线程停止
				test.stop();
				System.out.println("线程停止了=========");
			}
		}
	}

	
	public void run() {
		 int i=0;
		while(flag) {
			System.out.println("run在运行----------"+i++);
		}	
	}	
	
	//设置一个公开的方法停止线程,转换标志位
	public void stop() {
		this.flag=false;
	}
}

线程休眠:

sleep(时间)指定当前线程阻塞的毫秒数;

sleep存在异常InterruptedException;

sleep时间达到后线程进入就绪转台

sleep可以模拟网络延时,倒计时等

每一个对象都有一个锁,sleep不会释放锁

//模拟倒计时
public class StaticProxy {
	public static void main(String[] args) throws InterruptedException {
		tenDown();
	}
	
	public static void tenDown() throws InterruptedException {
		int num=10;
		while(true) {
			if(num>=0) {
				System.out.println(num);
				Thread.sleep(1000);
				num--;
			}
			else {
				break;
			}
		}
	}

}


//每隔一秒就输出一次系统当前时间
public class StaticProxy {
	public static void main(String[] args) throws InterruptedException {	
		Date currenttime=new Date(System.currentTimeMillis());
		while(true) {
			System.out.println(new SimpleDateFormat("hh:mm:ss").format(currenttime));
			Thread.sleep(1000);
			//每过一秒就刷新一下时间
			currenttime=new Date(System.currentTimeMillis());
	
		}
	}
}

线程礼让(yield)

礼让线程,让当前正在执行的线程暂停,但不阻塞

将线程从运行状态转为就绪状态

让cpu重新调度,礼让不一定成功,看cpu心情,我可以让让出,但是接下来我们一起争取

join

join合并线程,待这个线程执行完之后,其他线程才能继续执行

代码实现

public class StaticProxy implements Runnable{
	public static void main(String[] args) throws InterruptedException {	
		StaticProxy thread0 = new StaticProxy();
		StaticProxy thread1 = new StaticProxy();
		Thread t=new Thread(thread0);
		t.start();
		//不加这一句之前,线程的执行时,线程0和1是混乱的谁抢占上CPU了就执行谁
		t.join();
		new Thread(thread1).start();
	}
	
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(Thread.currentThread().getName()+"正在执行");
		}		
	}
	
}


//不加join的输出结果,在0执行过程中掺杂了1线程
Thread-0正在执行
Thread-1正在执行
Thread-0正在执行
Thread-0正在执行

//加了join的执行结果
会等待0线程执行完之后才执行1线程

线程的优先级:

java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度按照优先级决定应该调度那个线程来执行

线程的优先级用数字表示,范围从1-10

Thread.MIN_PRIORITY=1;

Thread.MAX_PRIORITY=10

Thread.NORM_PRIORITY=5;

使用一下方式改变线程或获取线程的优先级

getPriority().setPriority(int xxx)

优先级低只是意味着获取调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度

优先级的设置要在启动start()之前

守护线程:

线程分为用户线程和守护线程:

虚拟机必须确保用户线程执行完毕

虚拟机不用等待守护线程执行完毕

如,后台记录操作日志,监控内存,垃圾回收

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值