淘先锋技术网

首页 1 2 3 4 5 6 7

Java是一种流行的编程语言,具有高效、可扩展、并且支持多线程编程的特点。多线程编程使得程序可以同时执行多个任务,提高了程序的性能。Java中多线程编程的方式包括继承Thread类、实现Runnable接口和使用Executors框架等。

public class MyThread extends Thread {
public void run() {
// 执行任务
}
}
public class MyRunnable implements Runnable {
public void run() {
// 执行任务
}
}
public class MainClass {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
MyRunnable r1 = new MyRunnable();
Thread t2 = new Thread(r1);
t2.start();
Executor executor = Executors.newFixedThreadPool(10);
executor.execute(() ->{
// 执行任务
});
}
}

Scala是一种基于JVM的编程语言,拥有与Java相同的优点,并且以其优雅的函数式编程和扩展性而闻名。Scala中多线程编程的方式包括使用Actor模型和Future/Promise模型等。

import akka.actor.ActorSystem
import akka.actor.Props
import akka.actor.Actor
import scala.concurrent.Future
import scala.concurrent.Promise
import scala.concurrent.ExecutionContext.Implicits.global
case class Message(content: String)
class MyActor extends Actor {
def receive: Receive = {
case Message(content) =>// 执行任务
}
}
object MainObject {
def main(args: Array[String]): Unit = {
val actorSystem = ActorSystem("MyActorSystem")
val myActor = actorSystem.actorOf(Props[MyActor], "MyActor")
myActor ! Message("Hello Scala")
val p = Promise[String]()
val f = Future {
// 执行任务
"Done"
}
f.onSuccess { case result =>p success result }
f.onFailure { case t =>p failure t }
p.future
}
}