Java 多线程:synchronized关键字 简单实现同步

在实现多线程的时候,如果多个线程都对同一个变量进行访问,比如输出字符串,而且输出语句有多条,那么很可能会出现这种情况:A输出到一半,B又插进来输出,然后又是其他的线程插进来,那么输出会变得混乱

举个例子

可以看到输出语句是互相穿插的
在这里插入图片描述

import java.util.concurrent.*;

class printThread extends Thread {
	String thname;
	
	printThread(String threadName) {
		this.thname = threadName;
	}
	
	public void run() {
		System.out.print("0123456789");
		System.out.print("abcdefg");
		System.out.print("ABCDEFG");
		System.out.print("HelloWorld");
		System.out.print("7777777");
		System.out.print("XiaoXinMaZiLi");
		System.out.println();
	}
}

public class mutilThread {
	public static void main(String[] args) {
		ExecutorService pool = Executors.newCachedThreadPool();
		for(int i=0; i<100; i++) {
			printThread pt = new printThread(i+"");
			pool.submit(pt);
		}
		pool.shutdown();
	}
}

synchronized关键字实现同步代码块

当前线程访问的对象是 Obj,将对 Obj 的操作放在一下语句中间,可以实现对 Obj 对象的同步,即同一时间只能由一个线程操作 Obj 对象

synchronized(Obj) {
	// 要对 Obj 对象操作的语句
}
public void run() {
	synchronized(System.out) {
		System.out.print("0123456789");
		System.out.print("abcdefg");
		System.out.print("ABCDEFG");
		System.out.print("HelloWorld");
		System.out.print("7777777");
		System.out.print("XiaoXinMaZiLi");
		System.out.println();
	}
}

举个例子

在这里插入图片描述

import java.util.concurrent.*;

class printThread extends Thread {
	String thname;
	printThread(String threadName) {
		this.thname = threadName;
	}
	
	public void run() {
		synchronized(System.out) {
			System.out.print("0123456789");
			System.out.print("abcdefg");
			System.out.print("ABCDEFG");
			System.out.print("HelloWorld");
			System.out.print("7777777");
			System.out.print("XiaoXinMaZiLi");
			System.out.println();
		}
	}
}

public class mutilThread {
	public static void main(String[] args) {
		ExecutorService pool = Executors.newCachedThreadPool();
		for(int i=0; i<100; i++) {
			printThread pt = new printThread(i+"");
			pool.submit(pt);
		}
		pool.shutdown();
	}
}
发布了262 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44176696/article/details/105159373