模拟线程并发

模拟线程并发

并发包下的 java.util.concurrent.CountDownLatch
CountDownLatch 当这个变量不是0时,对应的线程进入堵塞状态,当着个变量为0 时,线程会接着往下执行(原子操作)

现模拟2000个线程,并发执行操作

package com.lcw;

import java.util.concurrent.CountDownLatch;

public class ThreadDemo {
    
    
	private static Integer TheardCount =2000;
	
	static CountDownLatch cld1 = new CountDownLatch(TheardCount);
	
	static CountDownLatch cld2 = new CountDownLatch(TheardCount);
	

	public static void main(String[] args) throws InterruptedException {
    
    
		
		long start =System.currentTimeMillis();
		for (int i = 0; i < TheardCount; i++) {
    
    
			Thread a =new Thread(new MyRunnable());
			a.start();
			// cld1减一
			cld1.countDown();
		}	
		//让主线程进入堵塞状态
		cld2.await();
		long end =System.currentTimeMillis();
		System.out.println(end-start+" 毫秒");
	}
	
public static class MyRunnable implements Runnable{
    
    	
		
		@Override
		public void run() {
    
    
			
			try {
    
    
				cld1.await();
				//让2000个线程进入堵塞
				System.out.println("模拟并发");
			} catch (InterruptedException e) {
    
    
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//修改 cld2 -1
			cld2.countDown();
		}
	}

}


如果使指定的线程优先执行有如下几种方法()
1.使用CountDownLatch计数,(run方法的执行顺序)
1.使用join();
3.使用wait();
4.使用线程锁,notify();

猜你喜欢

转载自blog.csdn.net/qq_38893133/article/details/103866888