Abi*_*Abi 6 java multithreading
我想在下面的程序中打印100作为输出.
我得到0作为答案.
class s extends Thread{
int j=0;
public void run() {
try{Thread.sleep(5000);}
catch(Exception e){}
j=100;
}
public static void main(String args[])
{
s t1=new s();
t1.start();
System.out.println(t1.j);
}
}
Run Code Online (Sandbox Code Playgroud)
tim*_*tes 13
你需要等待Thread到finish..I添加一个电话加入你,这将阻止和等待Thread,以观察前值完成j:
class s extends Thread{
int j=0;
public void run() {
try{ Thread.sleep(5000); } catch( Exception e ){}
j = 100;
}
public static void main(String args[]) throws InterruptedException {
s t1=new s();
t1.start();
t1.join() ; // Wait for t1 to finish
System.out.println(t1.j);
}
}
Run Code Online (Sandbox Code Playgroud)