package cn.itcast;
public class TraditionalThreadSynchronized {
public static void main(String[] args) {
new TraditionalThreadSynchronized().init();
}
private void init() {
final Outputer outputer = new Outputer();
new Thread(new Runnable() {
@Override
public void run() {
outputer.outputString("这是一个测试!!!");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
outputer.outputString("This is a test!!!");
}
}).start();
}
/*要保证两个方法及两个方法以上的代码同步性,必须用同一个对象作为同步代码块的锁*/
/*要想实现方法互斥分组,就是通过synchronized(obj)中的obj的不同来完成的*/
static class Outputer {
/*
* 也可以把整个方法作为同步代码块
* 像这样public synchronized void outputString(String name)
*/
public void outputString(String name) {
while (true) {
/*非静态方法的同步锁是this对象*/
synchronized (this) {
for (int i = 0; i < name.length(); i++) {
System.out.print(name.charAt(i));
}
}
System.out.println();
}
}
public void outputString2(String name) {
while (true) {
/*任何一个对象都可以作为同步代码块的锁*/
synchronized (new Object()) {
for (int i = 0; i < name.length(); i++) {
System.out.print(name.charAt(i));
}
}
System.out.println();
}
}
public static void outputString3(String name) {
while (true) {
/*静态方法的同步锁是类的字节码对象*/
synchronized (Outputer.class) {
for (int i = 0; i < name.length(); i++) {
System.out.print(name.charAt(i));
}
}
System.out.println();
}
}
}
}
synchronized
最新推荐文章于 2024-09-05 11:00:53 发布