多线程控制方法

1:start():用于开始执行run()方法中定义的线程体

2:sleep():调整java运行时间,指定调用线程的睡眠时间

3:jion():用于调用线程等待本线程结束

4: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 running
waiting for first thread to finishing...
Second thread starts running
Second thread suspends running
First thread finishes running
it is a long wait!
waking up second thread...
waking for second thread to finishing ...
Second thread run again and finishes 
i'm ready to finish too.


结果多种情况

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值