package com.demo;
public class ThreadDemo implements Runnable {
int num = 100;
byte[] lock = new byte[0];
public void run() {
//synchronized (this) { //使用代码块同步
for (int i = 0; i < 5000; i++) {
System.out.println(Thread.currentThread().getName() + " synchronized loop " + i);
synchronized(lock) {
num = num + 1;
}
}
}
//}
public static void print(Object obj){
System.out.println(obj);
}
public static void main(String[] args) throws InterruptedException {
ThreadDemo thread = new ThreadDemo();
Thread ta = new Thread(thread, "A");
Thread tb = new Thread(thread, "B");
ta.start();
tb.start();
Thread.currentThread().sleep(3000);
print(thread.num);
}
}