1、同时启动2个线程
public class TraditionalThreadSynchronized {
public static void main(String[] args) {
new TraditionalThreadSynchronized().init();
}
private void init(){
Output output = new Output();
new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
output.output("zhangsan");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
output.output("lisi");
}
}
}).start();
}
class Output{
public void output(String name){
int len = name.length();
for (int i=0;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
2个线程出现混乱情况
为了防止这种情况,可以在共同方法上加上synchronized关键字
public class TraditionalThreadSynchronized {
public static void main(String[] args) {
new TraditionalThreadSynchronized().init();
}
private void init(){
Output output = new Output();
new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
output.output("zhangsan");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
output.output("lisi");
}
}
}).start();
}
class Output{
public void output(String name){
int len = name.length();
synchronized (this){
for (int i=0;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
}