欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

在同一个类中,线程资源竞争

程序员文章站 2022-06-13 08:11:15
...

 

 

/**
 * 在同一个类中,线程资源竞争
 *
 */
public class ThreadTest12 implements Runnable {  
	
    public static ThreadTest12 test1;
    
    public static ThreadTest12 test2;
    
    public static void main(String[] args) throws InterruptedException {
    	new Thread(new ThreadTest12()).start();
    	//new Thread(new ThreadTest12()).start();
    	/*
    	1 都是 synchronized (test1)  
    	Thread-0
    	Thread-1
    	Thread-0start run1
    	Thread-0end   run1
    	Thread-1start run2
    	Thread-1end   run2
    	
    	2  一个是 synchronized (test1)  另一个是 synchronized (test2)
    	Thread-0
		Thread-1
		Thread-0start run1
		Thread-1start run2
		Thread-0end   run1
		Thread-1end   run2
    	 */


	}
    
    
    public static ThreadTest12 instentce() {
    	
    	String name = Thread.currentThread().getName();
		if ("Thread-0".equals(name)) {
			if (test1 == null) {
				test1 = new ThreadTest12();
			}
	    	return test1;
		} else {
			if (test2 == null) {
				test2 = new ThreadTest12();
			}
	    	return test2;
		}
    }
    
    private void run1() throws InterruptedException {
    	System.out.println(Thread.currentThread().getName());
    	synchronized (test1) {
    		System.out.println(Thread.currentThread().getName() + "start run1");
    		Thread.sleep(9900);
    		System.out.println(Thread.currentThread().getName() + "end   run1");
    		//ThreadTest12.instentce().run2();
        }
    }
    
    private void run2() throws InterruptedException {
    	System.out.println(Thread.currentThread().getName());
    	
    	// synchronized (test2)  没有发生资源竞争
    	synchronized (test1) { // 发生资源竞争
    		System.out.println(Thread.currentThread().getName() + "start run2");
    		Thread.sleep(9900);
    		System.out.println(Thread.currentThread().getName() + "end   run2");
        }
    }

	@Override
	public void run() {
		try {
			String name = Thread.currentThread().getName();
			if ("Thread-0".equals(name)) {
				ThreadTest12.instentce().run1();
			} else {
				ThreadTest12.instentce().run2();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

} 

 

 

 

 

 

 

 

 

 

 

相关标签: java