多个线程对同一资源进行操作的时候,有时候会带来问题,如下面
package Demo_1;
public class Mythread
{
public static void main(String[]args)
{
System.out.println(Thread.currentThread().getName());
Monster mt = new Monster();
Thread test1 = new Thread(mt);
Thread test2 = new Thread(mt);
Thread test3 = new Thread(mt);
test1.start();
test2.start();
test3.start();
}
}
class Monster implements Runnable
{
public int x = 1000;
public void run()
{
while(x>0)
{
try
{
Thread.sleep(1000);
/*synchronized (this)*/ {
System.out.println(Thread.currentThread().getName() + " x = "+ x);
x--;
}
}
catch(Exception e)
{
//
}
}
}
}
可以明显看到其中958出现两次。
只是因为这两句代码没有被原子的执行
System.out.println(Thread.currentThread().getName() + " x = "+ x);
x--;
synchronized(this)//对象锁
{
System.out.println(Thread.currentThread().getName() + " x = "+ x);
x--;
}