如何去控制多线程执行顺序

2019/11/13

如何去控制多线程执行顺序

例题:用2个线程如何让执行效果是ABBBABBBABBBABBBA。。。。

public class TestSoloution {
	
	public static void main(String[] args) throws InterruptedException {
		TestSoloution.init();
	}
	private static void init(){
		new Thread(){
			@Override
			public void run(){
				while(true){
					try {
						System.out.print("A");
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}finally{
					}
				}
			}
		}.start();
		new Thread(){
			@Override
			public void run(){
				while(true){
					try {
						System.out.print("B");
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}finally{
					}
				}
			}
		}.start();
		
	}
}

通过睡眠的方式一个线程执行时间和另一个是3倍关系就可以了。

Show Disqus Comments

Post Directory