我们知道当两个并发线程(thread1和thread2)访问同一个对象(syncThread)时,可以用synchronized加锁,代码如下:
public static void main(String[] args) {
SyncThread syncThread = new SyncThread();
Thread thread1 = new Thread( syncThread , "SyncThread1");
Thread thread2 = new Thread( syncThread , "SyncThread2");
thread1.start();
thread2.start();
}
public void run() {
{
for (int i = 0; i < 5; i++) {
try {
System.out.println("线程名:"+Thread.currentThread().getName() + ":" + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
但是如果访问的是不同对象,那么应该怎么去处理并发的情况,因为在实际应用中遇到了这种情况
public static void main(String[] args) {
System.out.println("使用关键字synchronized每次调用进行new SyncThread()");
SyncThread syncThread1 = new SyncThread();
SyncThread syncThread2 = new SyncThread();
Thread thread1 = new Thread(syncThread1, "SyncThread1");
Thread thread2 = new Thread(syncThread2, "SyncThread2");
thread1.start();
thread2.start();
}
```