package com.susan.thread;
/**
* 三、线程的互斥与同步问题 示例:字符输出
*
* @author dahai
*
*/
public class TraditionalThreadSynchronized {
public staticvoid main(String[] args) {
// TODO Auto-generated method stub
Outputer outputer =new Outputer();
new Thread(new Runnable() {
@Override
publicvoid run() {
//TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
outputer.output("fffffffffff");
}
}
}).start();
new Thread(new Runnable() {
@Override
publicvoid run() {
//TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
outputer.output2("gggggggggggg");
}
}
}).start();
}
}
/**
* 输出器
*
* @author dahai
*
*/
class Outputer {
// synchronized 同步锁 关键是同一个对象如 “Outputer” , string a等;
/**
* 方式一、
*
* @param name
*/
public void output(Stringname) {
//string a=“”;
//synchronized (a) { 用a不安全
//synchronized (this) { //锁对象
synchronized (Outputer.class) {//锁对象的字节码最靠谱
for (inti = 0; i < name.length();i++) {
System.out.print(name.charAt(i));
}
}
System.out.println();
}
/**
* 方式二、
*
* @param name
*/
public synchronizedvoid output1(String name) {
for (inti = 0; i < name.length();i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
/**
* 方式三、静态方法
* 静态方式 要想与方式一互斥,改为synchronized (Outputer.class)
* @param name
*/
public staticsynchronized void output2(String name) {
for (inti = 0; i < name.length();i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}