class Callme{
//synchronized void call(String msg){
void call(String msg){
System.out.print("[" + msg);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("Interrupted");
}
System.out.println("]");
}
}class Caller implements Runnable{
String msg;
Callme target;
Thread t;
public Caller(Callme targ,String s){
target = targ;
msg = s ;
t = new Thread(this);
t.start();
}
public void run(){
synchronized(target){
target.call(msg);
}
}
}public class Synch {
public static void main(String args[]){
Callme target = new Callme();
Caller ob1 = new Caller(target,"Hello");
Caller ob2 = new Caller(target,"Synchronized");
Caller ob3 = new Caller(target,"World");
try{ //即使去掉这段try代码,程序的输出也是相同的,这段代码究竟有什么作用呢?
ob1.t.join(); //请高手帮忙指点下迷津,万分感谢 hoho
ob2.t.join();
ob3.t.join();
}catch(InterruptedException e){
System.out.println("Interrupted");
}
}
}
//synchronized void call(String msg){
void call(String msg){
System.out.print("[" + msg);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("Interrupted");
}
System.out.println("]");
}
}class Caller implements Runnable{
String msg;
Callme target;
Thread t;
public Caller(Callme targ,String s){
target = targ;
msg = s ;
t = new Thread(this);
t.start();
}
public void run(){
synchronized(target){
target.call(msg);
}
}
}public class Synch {
public static void main(String args[]){
Callme target = new Callme();
Caller ob1 = new Caller(target,"Hello");
Caller ob2 = new Caller(target,"Synchronized");
Caller ob3 = new Caller(target,"World");
try{ //即使去掉这段try代码,程序的输出也是相同的,这段代码究竟有什么作用呢?
ob1.t.join(); //请高手帮忙指点下迷津,万分感谢 hoho
ob2.t.join();
ob3.t.join();
}catch(InterruptedException e){
System.out.println("Interrupted");
}
}
}
比如说吧:
main(){
long start = System.currentTimeMillis(); 很复杂的操作,开了许多其他的线程 long end=System.currentTimeMillis(); 如果要输出程序的运行时间,必须要等到所有的线程都结束,所以,main线程中要调用开启的线程的join方法,等待他们结束
}
{
......
t1.join();
t2.join();
然后再:
long end=System.currentTimeMillis();
.....
}
这样才可以
你输出结果之所以相同是因为synchronized(target)语句,注释掉后就会输出多种结果了
因为,3个线程共享一个Callme对象实例,而调用的时候是用synchronized锁定了这个对象,所以这3个线程只能异步的执行。 而你说的优先级跟这个没有关系。也没有规定必须等待子线程结束主线程才可以结束,我是说有的时候需要这么做。
/*
try{ //即使去掉这段try代码,程序的输出也是相同的,这段代码究竟有什么作用呢?
ob1.t.join(); //请高手帮忙指点下迷津,万分感谢 hoho
ob2.t.join();
ob3.t.join();
}catch(InterruptedException e){
System.out.println("Interrupted");
}
*/
System.out.println("over");现在你跑跑试试 就更清楚了