Public class ThreadTest{
public static void main(String args[ ]){
Xyz r= new Xyz( );
Thread t = new Thread( r );
t.start( );
}
}
Class Xyz implements Runnable{
int I ;
public void run( ){
while( true){
System.out.println(“Hello”+I++);
if (I==5) break ;
}
}
}
Public void doTask(){
TimerThread tt= new TimerThread(100) ;
tt.start( ) ;
…
// Do stuff in parallel with the other thread for a while
…
// Wait here for the timer thread to finish
try{
tt.join( );
} catch( InterruptedException e){ // tt came back early }
…
// continue in this thread
…
}
yield( )方法
调用该方法将CPU让给具有与当前线程相同优先级的线程。
如果没有同等优先级的线程是Runnable状态, yield( )方法将什么也不做。
线程同步
线程间同步机制
线程间的交互wait( ) 和notify( )
不建议使用的一些方法
多线程并发执行中的问题
多个线程相对执行的顺序是不确定的。
线程执行顺序的不确定性会产生执行结果的不确定性。
在多线程对共享数据 操作时常常会产生这种不确定性。
多线程并发执行中的问题
一个堆栈类
public class MyStack{
private int idx = 0 ;
private char[ ] data = new char[6] ;
public void push( char c ){
data[idx] = c ;
idx ++ ; // 栈顶指针指向下一个空单元
}
public char pop( ){
idx-- ;
return data[idx] ;
}
}
多线程并发执行中的问题
对象锁的概念
Java中每个对象都带有一个monitor标志,相当于一个锁。
Sychronized关键字用来给对象加上独占的排它锁。
对象锁的操作
Public void push(char c){
synchronized(this){
data[idx] = c ;
idx++ ;
}
}
对象锁的操作
示例
将MyStack 对栈的push,pop操作都采用这种机制:
public class MyStack{
…
public void push( char c ){
synchronized(this){
data[idx] = c ;
idx ++ ; }
}
public char pop( ){
synchronized(this){
idx-- ;
return data[idx] ;}
}
}
public class Reentrant {
public synchronized void a() {
b();
System.out.println("here I am, in a()");
}
public synchronized void b() {
System.out.println("here I am, in b()");
}
}
Java运行系统允许已经拥有某个对象所的线程再次获得该对象的锁——Java locks are reentrant.