5.8 实现代码块与函数之间的同步(非run和sale)

p { margin-bottom: 0.21cm; }

 

由于判断线程是否同步是使用的标识 我们可以根据这个原理对其他类进行同步处理

在一个线程中 一个线程执行了 start 方法不代表此线程就马上执行 只是此线程已经进入了可以执行状态 正真执行时需要处理器分配给此线程的执行

TestThead tethead = new TestThead();

new Thread(tethead).start();

new Thread(tethead).start();

调用类

public class TheadDemo1 {

public static void main(String[] args) {

TestThead tethead = new TestThead();

new Thread(tethead).start();

try {

// 让原来的线程暂停一毫秒 好cpu 执行tethead 线程

Thread.sleep(1);

} catch (InterruptedException e) {

e.printStackTrace();

}

tethead.setStr("method");

new Thread(tethead).start();

}

}

线程类

class TestThead /* implements Runnable */ extends Thread {

private String str = new String( "" );

int index = 100;

 

public String getStr() {

return str ;

}

 

public void setStr(String str) {

this . str = str;

}

 

public void run() {

// 用我们自己的办法 实现 sale 和代码块的同步

if ( str .equals( "method" )) {

while ( true ) {

synchronized ( this ) {

if ( index > 0) {

System. out .println( "run()"

+ Thread. currentThread ().getName() + " "

+ index );

super .run();

}

index --;

}

}

} else {

while ( true ){

sale();

}

}

}

 

// 实现 sale 方法实现线程同步

private synchronized void sale() {

if ( index > 0) {

System. out .println( "sale()" + Thread. currentThread ().getName()

+ " " + index );

}

// super.run();

index --;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值