Java多线程2--线程控制
2015-07-31 11:02
701 查看
1、sleep()方法
sleep()是一个静态方法,可以通过类名直接调用,会抛出InterruptedException
输出应该为5行“subThread is running”
2、join()方法
将一个进程合并到另一个进程中,相当于直接调用run()方法
subThread:0
subThread:1
subThread:2
MainThread:2
3、yield()方法
yield()方法用于让出cpu时间片给其他进程
4、setPriority()和getPriority()
设置进程优先级,优先级越高得到的cpu执行的时间片就越多,具体多少由操作系统分配
进程的优先级最高为10,最低为1,缺省值为5
sleep()是一个静态方法,可以通过类名直接调用,会抛出InterruptedException
public class testSleep { public static void main(String[] args) { subThread st = new subThread(); Thread t = new Thread(st); t.start(); try { //主进程sleep5s,然后调用thread类的interrupt方法, //t catch到InterruptedException,结束死循环 Thread.sleep(5000); t.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } } } class subThread implements Runnable{ public void run() { while(true){ System.out.println("subThread is running"); try { Thread.sleep(1000); } catch (InterruptedException e) { return; } } } }
输出应该为5行“subThread is running”
2、join()方法
将一个进程合并到另一个进程中,相当于直接调用run()方法
public class testJoin { public static void main(String[] args) throws InterruptedException { subThread1 st = new subThread1(); Thread t = new Thread(st); System.out.println("MainThread:1"); t.start(); t.join(); System.out.println("MainThread:2"); } } class subThread1 implements Runnable{ public void run() { for(int i=0;i<3;i++){ System.out.println("subThread:"+i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }运行结果为:MainThread:1
subThread:0
subThread:1
subThread:2
MainThread:2
3、yield()方法
yield()方法用于让出cpu时间片给其他进程
4、setPriority()和getPriority()
设置进程优先级,优先级越高得到的cpu执行的时间片就越多,具体多少由操作系统分配
进程的优先级最高为10,最低为1,缺省值为5
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树
- [原创]java局域网聊天系统