Java 线程的同步与死锁
/*
java 中线程 并发 将共同抢 CPU 资源 , 哪个抢到就运行 , 往往会有冲突 , 为了避免 , 引入线
程等待 sleep()
还有可以使用
join
方法 , 当前线程等待调用该方法的线程结束后 , 再恢复执行 , 见下面例
子, A 执行时, B.join 后, A
A
A
A 等 B
B
B
B 执行完后执行
当然还有可以 setPriority, getPriority 设置查看优先级
*/
class
class
class
class JoinThread implements
implements
implements
implements Runnable{
Thread A , B ;
String[] content ={ "
天气预报
" , "
多云转阴
" , "
有小雨
" , "
最高温度
15C" , "
最低
温度 5C" };
JoinThread(){
A = new
new
new
new Thread( this
this
this
this );
B = new
new
new
new Thread( this
this
this
this );
B .setName( " 预报员 " );
}
public
public
public
public void
void
void
void run(){
if
if
if
if (Thread.
currentThread
()== A ){
System.
out
.println( "
我等
" + B . getName ()+ "
说完话再说
" );
try
try
try
try {
B .join(); // 线程 A 开始等待 B 结束
} catch
catch
catch
catch (InterruptedException e){
}
System.
out
.println( "\n 我开始说话 :\' 我知道了,谢谢 \'" );
} else
else
else
else if
if
if
if (Thread.
currentThread
()== B ){
System.
out
.println( B . getName ()+ " 说: " );
for
for
for
for ( int
int
int
int i=0; i< content . length ; i++){
if
if
if
if (i!=0) System.
out
.print( "," );
System.
out
.print( content [i]);
try
try
try
try {
B .
sleep
(3000) ;
} catch
catch
catch
catch (InterruptedException e){
}
}
}
}
}
class
class
class
class ThreadTest{
public
public
public
public static
static
static
static void
void
void
void main(String args[]){
JoinThread a= new
new
new
new JoinThread();
a. A .start();