线程之synchronized 块

①同一个对象中的两个线程

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都处于执行状态

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值