可以。
Java 中的每个对象都有一个锁,当访问某个对象的synchronized方法时,表示将该对象上锁,
此时其他任何线程都无法访问该synchronized方法了,直到之前的那个线程方法完毕或是抛出了异常,
则该对象将锁释放掉,其他线程才可能去访问该synchronized方法。
如果一个对象有多个synchronized方法,某个线程已经进入到了某个synchronized方法,在该方法没有执行
完毕前,其他线程无法访问该对象的任何synchronized方法,但其它线程可进入此对象的其它方法。
请运行示例:
public class MyThreadTest
{
public static void main(String[] args)
{
Demo example = new Demo();
Thread t1 = new TheThread33(example);
Thread t2 = new TheThread44(example);
Thread t3 = new TheThread55(example);
t1.start();
t2.start();
t3.start();
}
}
class Demo
{
public synchronized void execute()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("hello: " + i);
}
}
public synchronized void execute2()
{
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("world: " + i);
}
}
public void output()
{
for (int x = 0; x < 10; x++)
{
try
{
Thread.sleep(600);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("你好啊");
}
}
}
class TheThread33 extends Thread
{
private Demo example;
public TheThread33(Demo example)
{
this.example = example;
}
@Override
public void run()
{
this.example.execute();
}
}
class TheThread44 extends Thread
{
private Demo example;
public TheThread44(Demo example)
{
this.example = example;
}
@Override
public void run()
{
this.example.output();
}
}
class TheThread55 extends Thread
{
private Demo example;
public TheThread55(Demo example)
{
this.example = example;
}
@Override
public void run()
{
this.example.execute2();
}
} |