java线程同步-同步方法
线程的同步是保证多线程安全访问竞争资源的一种手段。
对于同步,在具体的Java代码中需要完成一下两个操作:
把竞争访问的资源标识为private;
同步哪些修改变量的代码,使用synchronized关键字同步方法或代码。
实例:
package com.du20150310Synchr; public class Synchr { public static void main(String[] args) { User u = new User("张三",100); MyThread myThread1 = new MyThread("线程A",u,20); MyThread myThread2 = new MyThread("线程B",u,-20); MyThread myThread3 = new MyThread("线程C",u,60); MyThread myThread4 = new MyThread("线程D",u,-80); MyThread myThread5 = new MyThread("线程E",u,100); myThread1.start(); myThread2.start(); myThread3.start(); myThread4.start(); myThread5.start(); } } class MyThread extends Thread{ public MyThread() { } public MyThread(String name,User u, Integer y) { super(name); this.u = u; this.y = y; } private User u; private Integer y; @Override public void run() { u.oper(y); } } class User{ public User() { } public User(String name, Integer result) { this.name = name; this.result = result; } private String name; private Integer result; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getResult() { return result; } public void setResult(Integer result) { this.result = result; } @Override public String toString() { return super.toString(); } public synchronized void oper(int y){ try { Thread.sleep(10); this.result = this.result + y; System.out.println(Thread.currentThread().getName()+"\t运行结束,增加"+"'"+y+"'"+"\t余额为:"+this.result); Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } }
结果:
如果有使用请标明来源:http://www.cnblogs.com/duwenlei/