Java多线程编程核心技术02-线程安全

创建多个线程,拥有各自的成员变量

package com.learn;

public class Main02 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread a = new MyThread("A");
		MyThread b = new MyThread("B");
		MyThread c = new MyThread("C");
		
		a.start();
		b.start();
		c.start();
	}

}

class MyThread extends Thread {
	private int count = 5;
	
	public MyThread(String name) {
		this.setName(name);
	}
	
	@Override
	public void run() {
		while (count > 0) {
			count--;
			System.out.println(Thread.currentThread().getName() + " : " + count);
		}
	}
}

/*
 * output:
A : 4
A : 3
A : 2
C : 4
C : 3
C : 2
C : 1
C : 0
B : 4
B : 3
B : 2
B : 1
B : 0
A : 1
A : 0

 * */

多个线程同时处理同一个数据

package com.learn;

public class Main03 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread myThread = new MyThread();
		Thread a = new Thread(myThread, "A");
		Thread b = new Thread(myThread, "B");
		Thread c = new Thread(myThread, "C");
		
		a.start();
		b.start();
		c.start();
	}

}

class MyThread extends Thread {
	private int count = 5;
	
//	public MyThread(String name) {
//		this.setName(name);
//	}
	
	@Override
	public void run() {
		while (count > 0) {
			count--;
			System.out.println(Thread.currentThread().getName() + " : " + count);
		}
	}
}
/*
B : 3
B : 1
B : 0
C : 2
A : 3
*/

如果不加synchronized关键字,操作类的静态成员是非线程安全的。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部