线程的基本操作3
Posted zkfly
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程的基本操作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();
以上是关于线程的基本操作3的主要内容,如果未能解决你的问题,请参考以下文章