已解决
【Java并发编程五】线程的基本使用三
来自网友在路上 179879提问 提问时间:2023-11-20 00:46:48阅读次数: 79
最佳答案 问答题库798位专家为你答疑解惑
线程的管理
我们使用ThreadGroup对线程进行管理,ThreadGroup具有三个参数,ThreadGroup、Runnable、String:
public Thread(ThreadGroup group, Runnable target, String name)
例子:
package myTest;public class myTest implements Runnable {public static void main(String[] args) {// 线程组ThreadGroup tg = new ThreadGroup("myGroup");Thread t1 = new Thread(tg, new myTest(), "Thread1");Thread t2 = new Thread(tg, new myTest(), "Thread2");t1.start();t2.start();System.out.println(tg.activeCount());tg.list();}@Overridepublic void run() {String group = Thread.currentThread().getThreadGroup().getName()+"-"+Thread.currentThread().getName();while(true) {System.out.println("This is "+group);try {Thread.sleep(10000);} catch (InterruptedException e) {throw new RuntimeException(e);}}}
}
/**
2
java.lang.ThreadGroup[name=myGroup,maxpri=10]Thread[Thread1,5,myGroup]Thread[Thread2,5,myGroup]
This is myGroup-Thread2
This is myGroup-Thread1
*/
线程的后台
有些主线程在不断的消耗资源进行运算,而后台线程则负责资源垃圾的回收,等主线程结束以后,后台线程便会自然结束。设置后台线程的方法:
package myTest;public class myTest {public static class test1 implements Runnable {@Overridepublic void run() {try {Thread.sleep(5000);} catch (InterruptedException e) {throw new RuntimeException(e);}}}public static class test2 implements Runnable {@Overridepublic void run() {while (true) {System.out.println("I am alive");try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}}}}public static void main(String[] args) {Thread t1 = new Thread(new test1());Thread t2 = new Thread(new test2());t2.setDaemon(true);t1.start();t2.start();}
}
线程会在运行后,开始寻找主线程,等待主线程,如果发现没有主线程,或主线程已经结束,只有后台线程才存活,便会结束线程。
线程的优先级
常用控制着线程的优先级的方法为setPriority():
package myTest;public class myTest {public static class high implements Runnable {static int count = 0;@Overridepublic void run() {while(true) {synchronized (myTest.class) {count ++;if(count>10000) {System.out.println("high is win");break;}}}}}public static class low implements Runnable {static int count = 0;@Overridepublic void run() {while (true) {synchronized (myTest.class) {count ++;if(count>10000) {System.out.println("low is win");break;}}}}}public static void main(String[] args) {Thread t1 = new Thread(new high());Thread t2 = new Thread(new low());t1.setPriority(10);t2.setPriority(1);t1.start();t2.start();}
}
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"【Java并发编程五】线程的基本使用三":http://eshow365.cn/6-39815-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: 【Java 进阶篇】Ajax 入门:打开前端异步交互的大门
- 下一篇: iOS线程