package com.x.test;
/**
* @author lelonta
* @version 1.0
*/
public class threadsynchronized {
public static void main(String[] args) {
//调用init方法
new threadsynchronized().init();
}
public void init() {
//内部类不能在静态方法中创建对象
final Outputer outputer = new Outputer();
//内部类访问局部变量
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
outputer.output("hehe");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
outputer.output("haha");
}
}
}).start();
}
class Outputer {
public void output(String name) {
int len = name.length();
synchronized (this) {
//synchronized 实现了代码的互斥
// 及在有线程访问同一个资源的时候另一个线程必须等待
//就如厕所的坑一样 一个人占着 另一个人或者其他人必须等用的人用完才能用
//传的对象必须是唯一的
//传name不行 因为name可以传不同的参数
//传this 可以防止在外部调用 outputer 的方法不同
//例如 outputer.output("hehe");
// new Outputer.output("hehe");
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
}