线程同步
java中允许多线程并行访问,同一时间段内多个线程完成各自的操作。
多个线程同时操作同一个共享数据时,可能会导致不准确的问题。
使用线程同步可以解决上述问题。
可以通过synchronized关键字修饰方法实现线程同步,每个Java对象都有一个内置锁,内置锁会保护使用synchronized关键字修饰的方法,要调用该方法就必须先获得锁,否则就处于阻塞状态。
非线程同步
package com.mie.scynchronized;
/*
* 实现用户访问数据
*/
public class Account implements Runnable{
//静态成员变量number,属于共享数据。
private static int number;
//使用synchronized关键字修饰方法来实现线程同步。
@Override
public void run() {
// TODO Auto-generated method stub
//1.num操作
number++;
try {
//2.休眠一秒
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//3.打印输出
System.out.println(Thread.currentThread().getName()+"是当前的第"+number+"位访问者");
}
}
package com.mie.scynchronized;
import com.sun.webkit.ThemeClient;
public class Test {
public static void main(String[] args) {
Account account=new Account();
// Thread thread=new Thread(account,"张三");
// Thread thread2=new Thread(account,"李四");
// thread.start();
// thread2.start();
for (int i = 0; i < 10; i++) {
Thread thread=