这是我第一次写多线程程序。 我怀疑我创建的多个线程将指向相同的运行方法并执行run()中写入的任务。 但我想不同的线程来执行不同的任务 如1线程插入到数据库中其他更新等 我的问题是如何创造不同的线程将执行不同的任务多线程执行不同任务
2
A
回答
3
创建线程做不同的工作:
public class Job1Thread extends Thread {
@Override
public void run() {
// Do job 1 here
}
}
public class Job2Thread extends Thread {
@Override
public void run() {
// Do job 2 here
}
}
启动线程,他们会为你工作:
Job1Thread job1 = new Job1Thread();
Job2Thread job2 = new Job2Thread();
job1.start();
job2.start();
2
您可以创建实现Runnable不同的不同类别作业 - 仅用于开始
2
您可以根据您的条件(插入数据库,更新等)运行run()方法。在初始化线程类时,在类构造函数中传递参数,该参数将定义此线程将为您执行的任务。
0
您可以使用内部类此。如下所示
class first implements Runnable
{
public void run(){
System.out.println("hello by tobj");
}
public static void main(String args[]){
first obj=new first();
Thread tobj =new Thread(obj);
tobj.start();
Thread t2 =new Thread(obj)
{
public void run()
{
System.out.println("hello by t2");
}
};
Thread t = new Thread(obj)
{
public void run()
{
System.out.println("hello by t");
}
};
t.start();
t2.start();
}
}
+0
使用类的对象不是内部类所必需的,但它不会阻止你这样做。 –
1
/*该程序创建三个不同的线程来执行三个不同的任务。线程-1打印A ... Z,线程2打印1 ... 100,线程3打印100-200。用于理解多线程的非常基本的程序,而不为不同任务创建不同的类别*/
class ThreadingClass implements Runnable {
private Thread t;
private String threadName;
ThreadingClass(String name) {
threadName = name;
System.out.println("Creating " + threadName);
}
public void run() {
System.out.println("Running " + threadName);
if(threadName == "Thread-1"){
this.printAlpha();
}
else if(threadName == "Thread-2"){
this.printOneToHundred();
}
else{
this.printHundredMore();
}
}
public void printAlpha(){
for(int i=65; i<=90; i++)
{
char x = (char)i;
System.out.println("RunnableDemo: " + threadName + ", " + x);
}
}
public void printOneToHundred(){
for(int i=1; i<=100; i++)
{
System.out.println("RunnableDemo: " + threadName + ", " + i);
}
}
public void printHundredMore(){
for(int i=100; i<=200; i++)
{
System.out.println("RunnableDemo: " + threadName + ", " + i);
}
}
public void start() {
System.out.println("Starting " + threadName);
if (t == null) {
t = new Thread (this);
t.start();
t.setName(threadName);
}
}
}
public class MultiTasking {
public static void main(String args[]) {
ThreadingClass R1 = new ThreadingClass ("Thread-1");
ThreadingClass R2 = new ThreadingClass ("Thread-2");
ThreadingClass R3 = new ThreadingClass ("Thread-3");
R1.start();
R2.start();
R3.start();
}
}
相关问题
- 1. 如何让不同的OpenMP线程执行不同的任务
- 2. 线程任务不在IIS中执行
- 3. 正确使用JavaFX任务执行多线程和线程池
- 4. 多线程同步执行
- 5. 在不同线程中运行任务
- 6. 在iOS中的不同线程上执行后台任务
- 7. 细粒度多线程 - 工作任务应该执行多少?
- 8. 使Spring任务与任务执行器线程一起运行
- 9. Java线程任务的并发执行
- 10. 在UI线程上执行长任务
- 11. 在另一个线程执行任务
- 12. 执行任务时听线程
- 13. 在多线程环境中并行执行每个子任务
- 14. 执行相同任务的多个JButton
- 15. 同步执行多个任务
- 16. 多线程任务
- 17. 用于执行具有不同优先级的任意任务的线程池
- 18. 设计多线程程序通常会更好吗每个线程执行一系列任务还是执行多个任务的线程组?
- 19. 创建X线程,同时执行一个任务
- 20. 多线程和多任务
- 21. 线程安全传递整数到任务执行任务
- 22. OpenMP任务 - 阻止特定线程执行任务的方式?
- 23. 使用任务在多线程C#中执行异常跟踪
- 24. 使用一个线程多次执行特定任务C#
- 25. 任务继续执行多个任务
- 26. 同步grunt.js任务执行
- 27. 执行多个线程同时
- 28. 不同的执行任务的方式
- 29. 执行者服务多线程
- 30. 暂停线程,而另一个线程正在执行任务
问题是? –
实现'java.lang.Runnable' –