现在的位置: 首页 > 综合 > 正文

Lock线程锁

2018年02月13日 ⁄ 综合 ⁄ 共 837字 ⁄ 字号 评论关闭

Outputer.java

package com.entel.research;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Outputer
{
	Lock lock = new ReentrantLock();
	
	public void output(String name)
	{
		int length = name.length();
		
		lock.lock();
		
		try
		{
			for(int i=0;i<length;i++)
			{
				System.out.print(name.charAt(i));
			}
			System.out.println();
		}
		finally
		{
			lock.unlock();
		}
	}
}

JunitOutputer.java

package com.entel.research;

public class JunitOutputer
{
	public static void main(String[] args)
	{
		final Outputer outputer = new Outputer();
		
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				while(true)
				{
					try
					{
						Thread.sleep(100);
					}
					catch (InterruptedException e)
					{
						e.printStackTrace();
					}
					
					outputer.output("LiJian");
				}
			}
		}).start();
		
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				while(true)
				{
					try
					{
						Thread.sleep(100);
					}
					catch (InterruptedException e)
					{
						e.printStackTrace();
					}
					outputer.output("ZhangSan");
				}
			}
		}).start();
	}
}

抱歉!评论已关闭.