初涉java多线程(一)

十一期间看了一点java多线程,现在又回顾了一下。看书-->论坛-->看书 算是一个很好的学习步骤。把理解的DD写下来就理解的更实在了。

public class TestThread implements Runnable{
private String info;
public TestThread(){}
public TestThread(String s){
this.info=s;
}
public synchronized void setInfo(String s){
this.info=s;
}
public synchronized void printInfo(){
while (true) {
System.out.println("print info..." + info);
}
}
public void run(){
printInfo();
}
public static void main(String[] args) {
TestThread t=new TestThread("001");
Thread t1=new Thread(t); //thread one
TestThread tt=new TestThread("002");
Thread t2=new Thread(tt); //thread two
Thread t3=new Thread(new TestClass(t));//thread three

t1.start();
t2.start();
t3.start(); //never execute, cause the object of t is locked in thread t1

}

}
class TestClass implements Runnable{
private TestThread tt;
public TestClass(TestThread tt){
this.tt=tt;
System.out.println("get iiiiiiiiiiiiit...");//can execute
}
public void run(){
tt.setInfo("0000000007");//blocked
tt.printInfo();
}
}

代码运行后,根本看不到0000000007输出在控制值或命令行;而是001与002交替输出:synchronized 并不是锁住代码块or方法,否则只有一个一直输出。
t与tt是不同的对象,他们之间没有什么线程安全问题。
t1.start(); 由于调用了printInfo()同步方法,t对象关联的锁被线程一所得,无限循环的输出(运行)导致的结果是,线程一在程序运行期间不会释放t对象的锁;所以27行启动线程三后会一直阻塞于39行,因为线程一、三访问的是同一对象,线程一不释放锁,39行中线程三觊觎这把锁,只能阻塞了。
有人会问35行怎么能执行?这里只是把对象引用指向堆中对象,并没有访问对象(给对象传消息),所以35行能执行。(传递的是对象引用的拷贝)
倘若把第7行的synchronized去掉,那么就能看到0000000007输出在控制值或命令行;此时线程三并未顺利执行,线程三只是执行了39行,阻塞于40行;因为setInfo不是同步方法了,调用此方法时,线程不需要得到对象的关联锁;而40行调用printInfo()同步方法时,只能阻塞了:线程一还没有释放此对象的锁...
第7、10行的两个同步方法可写成下面的形式:

public void setInfo(String s){
synchronized(this){
this.info=s;
}
}
public void printInfo(){
synchronized(this){
while(true){
System.out.println("print info..."+info);
}
}
}

synchronized(this)是不是很形象了:对象要调用本方法,就锁住此对象。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值