线程的基本操作3

线程组:   当线程数量较多,且功能比较明确时可以将类似的线程放到一起.

public class ThreadGroupName implements Runnable{

	@Override
	public void run() {
		Thread thread = Thread.currentThread();
		String name = thread.getThreadGroup().getName()+" :  "+thread.getName();
		while(true) {
			System.out.println("S9世界赛" + name);
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		ThreadGroup group = new ThreadGroup("线程组");
		Thread thread1 = new  Thread(group, new ThreadGroupName(), "skt");
		Thread thread2 = new  Thread(group, new ThreadGroupName(), "fpx");
		thread1.start();
		thread2.start();
		System.out.println("活动的线程:"+group.activeCount()); //此为预估值,仅供参考
		group.list();
	}
}

 守护线程是一种特殊的线程,它默默地完成一些系统服务,  java应用中如果只有守护线程, JVM将会自动退出.

public class DaemonThread {
	
	public static class myThread extends Thread{
		@Override
		public void run() {
			while (true) {
				System.out.println("Daemon , I am runing !");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * y下面这个例子中, t1是守护线程, main是主线程, 当主线程运行完毕,整个程序自然结束.
	 * @param args
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws InterruptedException {
		myThread t1 = new myThread();
		t1.setDaemon(true); // 必须在start()之前设置, 不然当作工作线程去执行
		t1.start();
		Thread.sleep(2000);
	}
}

线程的优先级: 在要求严格的环境下, 还是需要自己在应用层去解决问题.

public class PrioRityThread {
	
	public static class LowThread extends Thread{
		int count =0;
		@Override
		public void run() {
			while(true) {
				synchronized (PrioRityThread.class) {
					count++;
					if(count > 1000000) {
						System.out.println("LowThread count: " + count);
						break;
					}
				}
			}
		}
	}
	
	public static class HeiThread extends Thread{
		int count =0;
		@Override
		public void run() {
			while(true) {
				synchronized (PrioRityThread.class) {
					count++;
					if(count > 1000000) {
						System.out.println("HeiThread count: " + count);
						break;
					}
				}
			}
		}
	}
	
	public static void main(String[] args) {
		LowThread lowThread = new LowThread();
		HeiThread heiThread = new HeiThread();
		//优先级从一到十, 优先级调度和底层操作系统有密切关系, 高优先级并不一定先执行!
		lowThread.setPriority(Thread.MIN_PRIORITY);
		heiThread.setPriority(Thread.MAX_PRIORITY);
		lowThread.start();
		heiThread.start();
	}

}

  

 

转载于:https://www.cnblogs.com/zkfly/p/11517187.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值