Mat*_*tin 45 java multithreading
我是线程的新手.我想创建一些与主线程分开工作的简单函数.但它似乎没有用.我只想创建新线程并在那里做一些独立于主线程上发生的事情.这段代码可能看起来很奇怪,但到目前为止我没有太多的线程经验.你能解释一下这有什么问题吗?
public static void main(String args[]){
test z=new test();
z.setBackground(Color.white);
frame=new JFrame();
frame.setSize(500,500);
frame.add(z);
frame.addKeyListener(z);
frame.setVisible(true);
one=new Thread(){
public void run() {
one.start();
try{
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
} catch(InterruptedException v){System.out.println(v);}
}
};
}
Run Code Online (Sandbox Code Playgroud)
sti*_*ike 91
您正在调用Thread one.start()方法中的run方法.但run只有在线程已经启动时才会调用该方法.改为:
one = new Thread() {
public void run() {
try {
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
} catch(InterruptedException v) {
System.out.println(v);
}
}
};
one.start();
Run Code Online (Sandbox Code Playgroud)
Bin*_*eng 16
你可以这样做:
Thread t1 = new Thread(new Runnable() {
public void run()
{
// code goes here.
}});
t1.start();
Run Code Online (Sandbox Code Playgroud)
小智 10
目标是编写代码以在一个地方调用start()和join().参数匿名类是一个匿名函数.new Thread(() ->{})
new Thread(() ->{
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
}){{start();}}.join();
Run Code Online (Sandbox Code Playgroud)
在匿名类的主体中有一个调用start()的instance-block.结果是一个Thread类的新实例,称为join().
你需要做两件事:
即
one.start();
one.join();
Run Code Online (Sandbox Code Playgroud)
如果你不这样做start(),什么都不会发生 - 创建一个Thread不会执行它.
如果你不这样做join),你的主线程可能会完成并退出,整个程序在另一个线程被安排执行之前退出.如果你不加入,它是否运行是不确定的.新线程通常可以运行,但有时可能无法运行.更好的确定.
| 归档时间: |
|
| 查看次数: |
135894 次 |
| 最近记录: |