解决线程安全问题--同步方法和静态同步方法
解决线程安全问题--同步方法
解决线程安全问题的一种方案:使用同步代码块格式:
synchronized(锁对象){
可能会出现线程安全问题的代码(访问了共享数据的代码)
}
注意:
1.通过代码块中的锁对象,可以使用任意的对象
2.但是必须保证多个线程使用的锁对象是同一个
3.锁对象作用:
把同步代码块锁住,只让一个线程在同步代码块中执行
public class RunnableImpl implements Runnable{ Object obj = new Object(); private int ticket = 100; //设置线程任务:卖票 @Override public void run() { //使用死循环,让卖票操作重复执行while(true){ //先判断票是否存在 while (true){ synchronized (obj){ payTicket(); } } } public synchronized void payTicket(){ if(ticket>0){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } //票存在,卖票ticket-- System.out .println(Thread.currentThread( ).getName()+"-->正在卖第" +ticket+"张票"+ticket--); } } }
public static void main(String[] args) { RunnableImpl runnable = new RunnableImpl(); Thread thread = new Thread(runnable); Thread thread1 = new Thread(runnable); Thread thread2 = new Thread(runnable); thread.start(); thread1.start(); thread2.start(); }
静态同步方法
public class SynchronizedStatic implements Runnable { static boolean staticFlag = true; public static synchronized void test0(){ for(int i=0;i<5;i++){ System.out.println("test0:"+Thread.currentThread().getName() + " "+ i); } } public void test1(){ synchronized (this) { // synchronized (SynchronizedStatic.class) { for(int i=0;i<5;i++){ System.out.println("test1:"+Thread.currentThread().getName() + " "+ i); } } } public void run() { if(staticFlag){ staticFlag = false; test0(); }else{ staticFlag = true; test1(); } } public static void main(String[] args) throws InterruptedException { SynchronizedStatic ss = new SynchronizedStatic(); new Thread(ss).start(); //保证第一条线程开始运行 // Thread.sleep(1); new Thread(ss).start(); } }
解决线程安全问题的一种方案:使用同步代码块格式:synchronized(锁对象){可能会出现线程安全问题的代码(访问了共享数据的代码)}注意:1.通过代码块中的锁对象,可以使用任意的对象2.但是必须保证多个线程使用的锁对象是同一个3.锁对象作用:把同步代码块锁住,只让一个线程在同步代码块中执行

浙公网安备 33010602011771号