package cn.thread;
public class Foo {
private int x = 100;
public int getX() {
return x;
}
public int fix(int y) {
x = x - y;
return x;
}
}
package cn.thread;
public class MyRunnable implements Runnable {
private Foo foo = new Foo();
public static void main(String[] args) {
MyRunnable run = new MyRunnable();
Thread ta = new Thread(run, "Thread-A");
Thread tb = new Thread(run, "Thread-B");
ta.start();
tb.start();
}
public void run() {
for (int i = 0; i < 3; i++) {
this.fix(30);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " : 当前foo对象的x值= " + foo.getX());
}
}
public int fix(int y) {
return foo.fix(y);
}
}
package cn.thread;
public class Foo2 {
private int x = 100;
public int getX() {
return x;
}
//同步方法
public synchronized int fix(int y) {
x = x - y;
System.out.println("线程"+Thread.currentThread().getName() + "运行结束,减少“" + y
+ "”,当前值为:" + x);
return x;
}
// //同步代码块
// public int fix(int y) {
// synchronized (this) {
// x = x - y;
// System.out.println("线程"+Thread.currentThread().getName() + "运行结束,减少“" + y
// + "”,当前值为:" + x);
// }
//
// return x;
// }
}
package cn.thread;
public class MyRunnable2 {
public static void main(String[] args) {
MyRunnable2 run = new MyRunnable2();
Foo2 foo2=new Foo2();
MyThread t1 = run.new MyThread("线程A", foo2, 10);
MyThread t2 = run.new MyThread("线程B", foo2, -2);
MyThread t3 = run.new MyThread("线程C", foo2, -3);
MyThread t4 = run.new MyThread("线程D", foo2, 5);
t1.start();
t2.start();
t3.start();
t4.start();
}
class MyThread extends Thread {
private Foo2 foo2;
/**当前值*/
private int y = 0;
MyThread(String name, Foo2 foo2, int y) {
super(name);
this.foo2 = foo2;
this.y = y;
}
public void run() {
foo2.fix(y);
}
}
}
public int fix(int y) {
synchronized (this) {
x = x - y;
}
return x;
}
public synchronized int getX() {
return x++;
}
public int getX() {
synchronized (this) {
return x++;
}
}
public static synchronized int setName(String name){
Xxx.name = name;
}
public static int setName(String name){
synchronized(Xxx.class){
Xxx.name = name;
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有