①同一个对象中的两个线程
package co.test.synchronize;
import java.util.ArrayList;
import java.util.List;
public class CopyOfTest implements Runnable {
private List<String> list = new ArrayList<String>();
private int count = 0;
public CopyOfTest(int whichThread) {
count = whichThread;
}
public static void main(String[] args) {
// 同一个对象中的两个线程-----------------------↓
CopyOfTest test = new CopyOfTest(0);
Thread thread1 = new Thread(test);
thread1.start();
Thread thread2 = new Thread(test);
thread2.start();
// 同一个对象中的两个线程-----------------------↑
}
@Override
public void run() {
if (count == 0) {
function3();
} else {
function4();
}
}
private void function3() {
count = 1;
synchronized (list) {
System.out.println("function33333 is start");
try {
// 模拟耗时操作
Thread.sleep(3000);
list.add("bb");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("function33333 is end");
}
}
private void function4() {
synchronized (list) {
System.out.println("function44444 is start");
System.out.println("list :" + list.size());
System.out.println("function44444 is end");
}
}
}
执行结果:
function33333 is start
function33333 is end
function44444 is start
list :1
function44444 is end
function4等function3执行完之后才被执行
②两个对象中的两个线程
package co.test.synchronize;
import java.util.ArrayList;
import java.util.List;
public class CopyOfTest implements Runnable {
private List<String> list = new ArrayList<String>();
private int count = 0;
public CopyOfTest(int whichThread) {
count = whichThread;
}
public static void main(String[] args) {
// 两个对象中的两个线程-----------------------↓
CopyOfTest test1 = new CopyOfTest(0);
CopyOfTest test2 = new CopyOfTest(1);
Thread thread1 = new Thread(test1);
thread1.start();
Thread thread2 = new Thread(test2);
thread2.start();
// 两个对象中的两个线程-----------------------↑
}
@Override
public void run() {
if (count == 0) {
function3();
} else {
function4();
}
}
private void function3() {
count = 1;
synchronized (list) {
System.out.println("function33333 is start");
try {
// 模拟耗时操作
Thread.sleep(3000);
list.add("bb");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("function33333 is end");
}
}
private void function4() {
synchronized (list) {
System.out.println("function44444 is start");
System.out.println("list :" + list.size());
System.out.println("function44444 is end");
}
}
}
执行结果:
function33333 is start
function44444 is start
list :0
function44444 is end
function33333 is end
function3和function4都处于执行状态