如何创建线程,简单代码

1、实现线程的方法:(1)继承Thread类重写run方法

                                      (2)实现Runnable接口重写un方法

                                      (3)实现Callable接口通过FutureTask包装器来创建Thread线程

                                      (4)利用线程池(newCachedThreadPool、newFixedThreadPool )

1、继承Thread类

(1)线程类
public class MyThread extends Thread {  
  public void run() {       //不会创建新的线程,相当于只是一个普通方法,由当前线程来调用
   System.out.println("MyThread.run()");  
  }  
}  
(2)测试类
MyThread myThread1 = new MyThread();  
MyThread myThread2 = new MyThread();  
myThread1.start();   //会创建新的线程
myThread2.start();  

       start方法是创建了新的线程,在新的线程中执行
       run方法是在主线程中执行该方法,和调用普通方法一样

2、实现Runnable接口

当前类如果已经继承一个父类,可以通过实现Runnable接口实现线程的创建

(1)线程类

public class MyThread extends A implements Runnable {

         public void run() {

            System.out.println("线程执行");  

(2)测试类

   MyThread s1=new MyThread();

   Thread t1 =new Thread(s1);

    t1.start();

}

3、实现Callable接口

(1)线程类

public class MyThread  extends OtherClass implements Callable<Integer> {
 
public Integer call() throws Exception {
      return 1;
 }

(2)测试类

Callable<Integer> oneCallable = new SomeCallable<Integer>();   
//由Callable<Integer>创建一个FutureTask<Integer>对象:   
FutureTask<Integer> oneTask = new FutureTask<Integer>(oneCallable);   
//FutureTask<Integer>是一个包装器,它通过接受Callable<Integer>来创建,它同时实现了Future和Runnable接口。    
Thread oneThread = new Thread(oneTask);   
oneThread.start();     
   
4、 newCachedThreadPool线程池

(1)匿名类方式

      ExecuteService  a=Executors.newCachedThreadPool();
              a.execute(new Runnable(){
                        public void run(){
                                 System.out.println("一个线程");

                       }
              });

(2)普通类方式

测试类

          ExecutorService service = Executors.newFixedThreadPool(2);//包含2个线程对象

         MyRunnable r = new MyRunnable();
         service.submit(r);

线程类

public class MyRunnable implements Runnable {
    public void run() {
           System.out.println("一个线程");    
    }    
}
在不同的编程语言中,创建线程的方式有所不同。以下是几种常见编程语言中创建线程的示例代码: ### Python Python 提供了 `threading` 模块来支持多线程编程。以下是一个创建线程并执行的示例: ```python import threading def print_numbers(): for i in range(1, 6): print(i) # 创建线程 thread = threading.Thread(target=print_numbers) # 启动线程 thread.start() # 等待线程执行完成 thread.join() ``` ### C++ 在 C++ 中,可以使用标准库中的 `<thread>` 来创建线程。以下是一个简单的示例: ```cpp #include <iostream> #include <thread> void print_numbers() { for (int i = 1; i <= 5; ++i) { std::cout << i << std::endl; } } int main() { // 创建线程 std::thread t(print_numbers); // 等待线程执行完成 t.join(); return 0; } ``` ### Java Java 提供了 `Thread` 类来支持多线程编程。以下是一个创建线程并执行的示例: ```java public class Main { public static void main(String[] args) { Thread thread = new Thread(() -> { for (int i = 1; i <= 5; i++) { System.out.println(i); } }); // 启动线程 thread.start(); try { // 等待线程执行完成 thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } ``` ### C# C# 提供了 `System.Threading` 命名空间来支持多线程编程。以下是一个创建线程并执行的示例: ```csharp using System; using System.Threading; class Program { static void PrintNumbers() { for (int i = 1; i <= 5; i++) { Console.WriteLine(i); } } static void Main() { // 创建线程 Thread thread = new Thread(new ThreadStart(PrintNumbers)); // 启动线程 thread.Start(); // 等待线程执行完成 thread.Join(); } } ``` ### 仓颉语言 在仓颉语言中,可以使用 `Future<T>` 来管理线程并获取线程的执行结果。以下是一个简单的示例: ```cangjie // 定义一个函数,用于打印数字 func printNumbers(): void { for i in 1..5 { print(i) } } // 创建并启动线程 val future = Future<Void>(printNumbers) // 等待线程执行完成 future.wait() ``` 这些示例展示了如何在不同的编程语言中创建线程并执行任务。需要注意的是,多线程编程中涉及到的线程同步和资源共享问题需要特别注意,以避免出现竞态条件和死锁等问题[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值