下面是一个具有同步功能的多线程示例,这是和上篇文章同样的例子,它依次打印计数器值,每次运行它时,它产生相同的结果。
class printdemo {
public void printcount() {
try {
for(int i = 5; i > 0; i--) {
system.out.println("counter --- " + i );
}
}catch (exception e) {
system.out.println("thread interrupted.");
}
}
}
class threaddemo extends thread {
private thread t;
private string threadname;
printdemo pd;
threaddemo( string name, printdemo pd) {
threadname = name;
pd = pd;
}
public void run() {
synchronized(pd) {
pd.printcount();
}
system.out.println("thread " + threadname + " exiting.");
}
public void start () {
system.out.println("starting " + threadname );
if (t == null) {
t = new thread (this, threadname);
t.start ();
}
}
}
public class testthread {
public static void main(string args[]) {
printdemo pd = new printdemo();
threaddemo t1 = new threaddemo( "thread - 1 ", pd );
threaddemo t2 = new threaddemo( "thread - 2 ", pd );
t1.start();
t2.start();
// wait for threads to end
try {
t1.join();
t2.join();
}catch( exception e) {
system.out.println("interrupted");
}
}
}
每次运行此程序时都会产生相同的结果 -
starting thread - 1
starting thread - 2
counter --- 5
counter --- 4
counter --- 3
counter --- 2
counter --- 1
thread thread - 1 exiting.
counter --- 5
counter --- 4
counter --- 3
counter --- 2
counter --- 1
thread thread - 2 exiting.