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 --;
}
}