关于对synchronized的理解


 当一个线程进入一个对象的一个synchronized方法后,其它线程是否可进入此对象的其它方法?

今天在论坛中看见这道题,开始也很模糊,最后写了个程序得出如下答案。

如果是同步方法的话是不可以的。
如果是非同步方法的话是可以的。
下面贴出代码:

package Test;

public class Test1
{
	public static void main(String[] args)
	{
		ThreadDemo threadDemo=new ThreadDemo();
		Thread t1=new ThreadOne(threadDemo);
		Thread t2=new ThreadTwo(threadDemo);
		Thread t3=new ThreadThree(threadDemo);
		t1.start();
		t2.start();
		t3.start();

	}

}

class ThreadDemo
{

	public synchronized void method1()
	{
		for (int i = 0; i < 10; i++)
		{
			try
			{
				Thread.sleep(500);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println("同步方法1"+"    "+ i);
		}
	}

	public synchronized void method2()
	{
		for (int i = 0; i < 10; i++)
		{
			try
			{
				Thread.sleep(500);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println("同步方法2"+"    " + i);
		}
	}

	public void Print()
	{
		for (int i = 0; i < 10; i++)
		{
			try
			{
				Thread.sleep(500);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println("非同步方法" + i);
		}
	}
}

class ThreadOne extends Thread
{
	private ThreadDemo threadDemo;

	public ThreadOne(ThreadDemo threadDemo)
	{
		this.threadDemo = threadDemo;
	}

	public void run()
	{
		this.threadDemo.method1();
	}
}

class ThreadTwo extends Thread
{
	private ThreadDemo threadDemo;

	public ThreadTwo(ThreadDemo threadDemo)
	{
		this.threadDemo = threadDemo;
	}

	public void run()
	{
		this.threadDemo.method2();
	}
}

class ThreadThree extends Thread
{
	private ThreadDemo threadDemo;

	public ThreadThree(ThreadDemo threadDemo)
	{
		this.threadDemo = threadDemo;
	}

	public void run()
	{
		this.threadDemo.Print();
	}

}


定义ThreadDemo类 有三个方法metho1,method2,Print。
其中metho1,method2为同步方法。Print为非同步方法。
如果在主函数中只开启t1.start()和t2.start();则输出结果为
t1输出完后,t2在输出。所以如果是同步方法的话是不可以的。

如果在主函数中只开启t1.start()和t3.start();则输出结果为
t1,Print交替输出。所以如果是非同步方法的话是可以的。

---------------------- android培训java培训、期待与您交流! ----------------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值