我是OSGI的新手,我目前的目标。我有10个帖子,它在一个文件中写下他们的名字。录制线程后随机休眠0..1秒。这一切都必须是捆绑。我创造它,但我不确定这是否正确。有什么意见吗?
package helloworld;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import writer.StartThreads;
public class Activator implements BundleActivator {
public void start(BundleContext context) throws Exception {
System.out.println("Start Thred!!");
new StartThreads().Execute();
}
public void stop(BundleContext context) throws Exception {
System.out.println("Goodbye World!!");
}
}
1
package writer;
import writer.WriterLogs;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class StartThreads {
public static void Execute() {
BufferedWriter writer = null;
File textFile = new File("threadLog.txt");
// if file doesnt exists, then create it
if (!textFile.exists()) {
try {
textFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
writer = new BufferedWriter(new FileWriter(textFile, true));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
WriterLogs wrt = new WriterLogs(writer);
Thread worker = new Thread(wrt);
worker.setName("Nisha-" + i);
worker.start();
try {
worker.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2
package writer;
import java.io.BufferedWriter;
import java.io.IOException;
public class WriterLogs implements Runnable {
private BufferedWriter writer;
public WriterLogs(BufferedWriter wr) {
this.writer = wr;
}
@Override
public void run() {
try
{
try {
synchronized(this.writer) {
this.writer.write(Thread.currentThread().getName() + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set random 0...1 s.
Thread.sleep((long)(Math.random() * 1000));
System.out.println(Thread.currentThread().getName());
}
catch (InterruptedException interruptedException)
{
/*Interrupted exception will be thrown when a sleeping or waiting
* thread is interrupted.
*/
System.out.println( Thread.currentThread().getName() +interruptedException);
}
}
}
答案 0 :(得分:3)
这不正确。就像蜘蛛所说的鲍里斯一样,当你的捆绑停止时,你应该释放任何资源并停止捆绑所做的任何处理。因此,从stop
方法,您应该以某种方式表示您的线程尽快停止。
在实践中,您可能会让代码运行,但这绝对不是您应该如何在OSGi中编写代码(这就是您所要求的)。