线程安全
非线程安全主要是指多个线程对同一个对象中 的同一个实例变量进行操作时会出现值被更改、值不同步的情况,进而影响程序的执行流 程。
/**
* Allocates a new {@code Thread} object. This constructor has the same
* effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
* {@code (null, target, name)}.
*
* @param target
* the object whose {@code run} method is invoked when this thread
* is started. If {@code null}, this thread's run method is invoked.
*
* @param name
* the name of the new thread
*/
public Thread(Runnable target, String name) {
init(null, target, name, 0);
}
实现多线程的资源共享:
public class Test {
public static void main(String[] args) {
Thread1 thread1 = new Thread1();
Thread a = new Thread(thread1, "A");
Thread b = new Thread(thread1, "B");
Thread c = new Thread(thread1, "C");
Thread d = new Thread(thread1, "D");
Thread e = new Thread(thread1, "E");
a.start();
b.start();
c.start();
d.start();
e.start();
}
}
线程定义:
public class Thread1 extends Thread {
private int count=5;
@Override
public void run() {
super.run();
count--;
System.out.println(Thread.currentThread().getName() + " is running!");
System.out.println(Thread.currentThread().getName() + " count: " + count);
}
}
虽然共享了资源,但是对资源count的访问是不同步的。
A is running!
A count: 2
C is running!
B is running!
C count: 0
E is running!
D is running!
E count: 0
B count: 0
D count: 0
解决资源同步问题的一个方法是在更改资源的操作的方法前加上synchronized修饰符,表示对该方法的调用必须进行锁的争抢,只有一个线程能够进行方法的调用。
@Override
synchronized public void run() {
super.run();
count--;
System.out.println(Thread.currentThread().getName() + " count: " + count);
System.out.println(Thread.currentThread().getName() + " is running!");
}