多线程示例

public class Test implements Runnable{
    int i=100;
    
	public static void main(String [] args){
		Test th = new Test();
		new Thread(th,"sf2:").start();
		new Thread(th,"sf1:").start();
		new Thread(th,"sf3:").start();
		new Thread(th,"sf4:").start();
		new Thread(th,"sf5:").start();
		new Thread(th,"sf6:").start();
		new Thread(th,"sf7:").start();
		new Thread(th,"sf8:").start();
		new Thread(th,"sf9:").start();
		new Thread(th,"sf10:").start();
		
	}
	
	/**
	 * 守护线程
	 */
	public synchronized void run(){
			for(;i<1000;i++){
				System.out.println(Thread.currentThread().getName()+i);
		}
			System.out.println(Thread.currentThread().getName());
	}
}

结果
sf2:100
sf2:101
sf2:102
sf2:103
.....
sf2:999
sf2:
sf10:
sf9:
sf8:
sf7:
sf6:
sf5:
sf4:
sf3:
sf1:


在使用synchronized关键字时候,应该尽可能避免在synchronized方法或synchronized块中使用sleep或者yield方法,因为synchronized程序块占有着对象锁,你休息那么其他的线程只能一边等着你醒来执行完了才能执行。不但严重影响效率,也不合逻辑。
同样,在同步程序块内调用yeild方法让出CPU资源也没有意义,因为你占用着锁,其他互斥线程还是无法访问同步程序块。当然与同步程序块无关的线程可以获得更多的执行时间。

猜你喜欢

转载自zhihchen.iteye.com/blog/1560792