标签:com 结束 sync read cat java static dea print
文件名:DeadThreadByExtend.java
注:
1、起线程的时候用的是start方法,run方法也可以调用,但是仅仅相当于普通调用,在当前线程内执行。
2、synchronized 不能直接修饰变量。
3、synchronized 块并不会强制块内变量的单线程访问。仅仅意味着在执行块内语句时锁住synchronized (args)的参数,直到执行结束才释放。
package com.ycf.study.thread;
class Sources{
int a;
public void setA(int x) {
synchronized (this) {
this.a = x;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class DeadThreadByExtend {
public static void main(String[] args) {
Sources s1 = new Sources();
Sources s2 = new Sources();
class MyThread1 extends java.lang.Thread {
@Override
public void run() {
System.out.println("线程1开始");
synchronized (s1) {
System.out.println("线程1申请修改s1");
s1.setA(20);
System.out.println("线程1修改完成");
System.out.println("线程1申请修改s2");
s2.setA(10);
System.out.println("线程1修改s2完成");
}
System.out.println("线程1退出并释放锁++++++++++");
}
}
class MyThread2 extends java.lang.Thread {
@Override
public void run() {
System.out.println("线程2开始");
synchronized (s2) {
System.out.println("线程2申请修改s2");
s2.setA(20);
System.out.println("线程2修改s2完成");
System.out.println("线程2申请修改s1");
s1.setA(10);
System.out.println("线程2修改s1完成");
}
System.out.println("线程2退出并释放锁++++++++++");
}
}
MyThread1 mt1 = new MyThread1();
MyThread2 mt2 = new MyThread2();
mt1.start();
mt2.start();
}
}
java学习群669823128
标签:com 结束 sync read cat java static dea print
原文地址:http://www.cnblogs.com/rese-t/p/7857812.html