码迷,mamicode.com
首页 > 编程语言 > 详细

线程的基本操作3

时间:2019-09-13 19:27:09      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:interrupt   todo   priority   int   系统服务   pre   应用   rri   dex   

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

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();
	}

}

  

 

线程的基本操作3

标签:interrupt   todo   priority   int   系统服务   pre   应用   rri   dex   

原文地址:https://www.cnblogs.com/zkfly/p/11517187.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!