首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 开源软件 >

多线程统制方法

2012-07-04 
多线程控制方法1:start():用于开始执行run()方法中定义的线程体2:sleep():调整java运行时间,指定调用线程

多线程控制方法

1:start():用于开始执行run()方法中定义的线程体
2:sleep():调整java运行时间,指定调用线程的睡眠时间
3:join():用于调用线程等待本线程结束
4:yield():暂时停止调用线程并将其放在队列末尾,等待另一轮执行,使同一优先级的其他线程有机会运行

ps:join和yield可以理解为是一对反义词。

下面看代码:

?

import java.io.PrintWriter;public class MethodTest {static PrintWriter out = new PrintWriter(System.out, true);public static void main(String[] args) {FristThread frist = new FristThread();SecondThread second = new SecondThread();frist.start();second.start();try {out.println("waiting for first thread to finishing...");frist.join();out.println("it is a long wait!");out.println("waking up second thread...");synchronized (second) {second.notify();}out.println("waking for second thread to finishing ...");second.join();} catch (InterruptedException e) {e.printStackTrace();}out.println("i'm ready to finish too.");}}class FristThread extends Thread {public void run() {MethodTest.out.println("First thread starts running");try {sleep(10000);} catch (InterruptedException e) {e.printStackTrace();}MethodTest.out.println("First thread finishes running");}}class SecondThread extends Thread {public synchronized void run() {MethodTest.out.println("Second thread starts running");MethodTest.out.println("Second thread suspends running");try {wait();} catch (InterruptedException e) {e.printStackTrace();}MethodTest.out.println("Second thread run again and finishes ");}}

?结果:

?

First thread starts runningwaiting for first thread to finishing...Second thread starts runningSecond thread suspends runningFirst thread finishes runningit is a long wait!waking up second thread...waking for second thread to finishing ...Second thread run again and finishesi'm ready to finish too.

热点排行