java 同步块关键字_Java同步关键字,同步方法和块

java 同步块关键字Java synchronized keyword is used in multithreading to create a code block that can be executed by only one thread at a time. Java同步关键字用于多线程中,以创建一个代码块,该代码块一次只能由一个线程执行。 为什么需要同步? (Why do w...
摘要由CSDN通过智能技术生成

java 同步块关键字

Java synchronized keyword is used in multithreading to create a code block that can be executed by only one thread at a time.

Java同步关键字用于多线程中,以创建一个代码块,该代码块一次只能由一个线程执行。



为什么需要同步? (Why do we need Synchronization?)

When we have multiple threads working on a shared entity, the end result might be corrupt. Let’s say we have a simple program to increase the counter variable of the object. This variable is shared across all the threads.

当我们有多个线程在一个共享实体上工作时,最终结果可能会损坏。 假设我们有一个简单的程序来增加对象的计数器变量。 该变量在所有线程之间共享。

package com.journaldev.threads;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class CounterThread implements Runnable {

	private int count;

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	@Override
	public void run() {
		Random rand = new Random();
		try {
			Thread.sleep(rand.nextInt(1000));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		count++;
	}

	public static void main(String[] args) throws InterruptedException {
		CounterThread ct = new CounterThread();

		List<Thread> threads = new ArrayList<>();
		for (int i = 0; i < 100; i++) {
			Thread t = new Thread(ct);
			threads.add(t);
			t.start();
		}
		// wait for every thread to finish
		for (Thread t : threads) {
			t.join();
		}

		System.out.println("Final Count = " + ct.getCount());
	}
}

We are using Thread join() method to make sure every thread is dead before we print the final count.

我们正在使用Thread join()方法来确保每个线程都已死,然后再打印最终计数。

We are also using Random class to add some processing time in the run() method.

我们还使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值