多线程任务

线程和进程
进程指内存中运行的应用程序,每个进程都有独立的内存空间
线程是进程中的执行路径,共享一个内存空间,线程之间自由切换,并发执行,一个进程最少有一个线程,线程是在进程基础上进一步划分,一个进程启动后里面的若干路径可以划分为若干线程。
创建线程的三种方式;
第一种继承Thread类:run()方法是线程要执行的任务方法,start()方法用来启动线程

   public static void main(String[] args)  {
        MyThread2 mt=new MyThread2();
        Thread t=new Thread(mt);
        t.start();
    }
}
class MyThread2 extends Thread{
    public void run(){
        System.out.println("创建线程");
   }

第二种是实现Runnable接口:

   public static void main(String[] args)  {
        MyThread2 mt=new MyThread2();
        Thread t=new Thread(mt);
        t.start();
    }
}
class MyThread2 implements Runnable{
    public void run(){
        System.out.println("创建线程");
   }

第三种是实现Callable<>接口,与FutrueTask连用

 public static void main(String[] args) throws ExecutionException, InterruptedException {
         MyCallable mc=new MyCallable();
        FutureTask<Integer> ft=new FutureTask<>(mc);
        Thread t=new Thread(ft);
           t.start();//子线程开始执行
```class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        for(int i=0;i<10;i++){
            System.out.println(i);
            Thread.sleep(100);
        }
        return 300;
    }
}

实现 Runnable 与 继承 Thread 相比有如下优势:**
通过创建任务的方式,然后给线程分配任务来实现多线程,更加适合多个线程同时执行相同任务的情况
可以避免单继承带来的局限性,任务与线程本身分离,提高了程序健壮性。
设置当前线程名称: Thread.currentThread().setName(“111”);
获取当前线程名称: Thread.currentThread().getName();
中断线程interrupt()
如果该线程阻塞的调用wait() , wait(long) ,或wait(long, int)的方法Object类,或的join() , join(long) , join(long, int) , sleep(long) ,或sleep(long, int) ,这个类的方法,那么它的中断状态将被清除,并且将收到InterruptedException 。 如果在InterruptibleChannel上的I / O操作中阻止该线程,则通道将关闭,线程的中断状态将被设置,线程将收到ClosedByInterruptException 。
用户线程和守护线程:
当一个进程不包含任何的存活的用户线程时,进程就结束
守护线程:守护用户线程,当最后一个用户线程结束时,所有的守护线程都自动死亡(骑士与公主的关系)线程调用setDaemon(boolean on)方法。如果参数为 true ,则将此线程标记为守护程序线程,把线程设置为守护线程,需要在start();方法之前设置。
实现线程安全有三种方式:
第一种同步代码块

以售票为例子:

public static void main(String[] args)  {
        //一个任务三个线程执行
        MyThread2 mt=new MyThread2();
        Thread t=new Thread(mt);
        Thread t2=new Thread(mt);
        Thread t3=new Thread(mt);
        t.start();
        t2.start();
        t3.start();
    }
}
class MyThread2 implements Runnable{
    int count=10;
    boolean flag=true;
    byte[] b=new byte[0];
    public void run(){
        while (flag){
            synchronized (b){
                syn();
            }`

 public void syn(){
        if(count>0){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            count--;
            System.out.println(Thread.currentThread().getName()+"余票"+count);
        }else {
            flag=false;
        }
    }

第二种: 同步方法

 public synchronized boolean syn(){//方法上添加synchronized
        if(count>0){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            count--;
            System.out.println(Thread.currentThread().getName()+"余票"+count);
            return true;
        }
        return false;
    }
 public static void main(String[] args)  {
        //一个任务三个线程执行
        MyThread2 mt=new MyThread2();
        Thread t=new Thread(mt);
        Thread t2=new Thread(mt);
        Thread t3=new Thread(mt);
        t2.start();
        t.start();
        t3.start();
    }
}
class MyThread2 implements Runnable{
    int count=10;
    public void run(){
        while (true){
          boolean s = syn();
          if(s==false){
              break;
          }
        }
   }

第三种:Lock锁机制, 通过创建Lock对象,采用lock()加锁,unlock()解锁,来保护指定的代码

class MyThread2 implements Runnable{
    int count=10;
    Lock l=new ReentrantLock(true);//创建lock对象
    public void run(){
        while (true){
            l.lock();//加锁
            if(count>0){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count--;
                System.out.println(Thread.currentThread().getName()+"余票"+count);
            }else {
                break;
            }
            l.unlock();//解锁
        }
   }

线程分为六种状态:Thread state

  • new 没启动的状态
  • Runnable 运行时
  • blocked 阻塞,排队时,排完队回到运行状态
  • waiting 无限期等待状态,可以被其他线程唤醒,醒了回到运行状态
  • timed waiting 指定时间的等待
  • terminated 结束











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
易语言是一种面向过程的编程语言,它并不直接支持多线程编程。但是,我们可以通过使用任务队列来模拟多线程的效果。 任务队列是一种数据结构,用于存储待执行的任务。在易语言中,我们可以使用数组或链表来实现任务队列。具体实现步骤如下: 1. 创建一个任务队列,用于存储待执行的任务。 2. 创建一个线程,用于从任务队列中取出任务并执行。 3. 在主线程中,将需要执行的任务添加到任务队列中。 4. 线程会循环地从任务队列中取出任务并执行,直到任务队列为空。 以下是一个简单的易语言多线程任务队列的示例代码: ``` ' 定义任务队列 Dim taskQueue() As String ' 定义互斥锁 Dim mutex As Integer ' 定义线程函数 Function ThreadFunc() While True ' 加锁 Lock mutex ' 判断任务队列是否为空 If UBound(taskQueue) > 0 Then ' 取出任务并执行 Dim task As String task = taskQueue(1) Call ExecuteTask(task) ' 移除已执行的任务 For i = 1 To UBound(taskQueue) - 1 taskQueue(i) = taskQueue(i + 1) Next i ReDim Preserve taskQueue(UBound(taskQueue) - 1) End If ' 解锁 Unlock mutex ' 等待一段时间再继续执行 Sleep 100 Wend End Function ' 执行任务的函数 Sub ExecuteTask(task As String) ' 执行任务的代码 End Sub ' 主程序 Sub Main() ' 初始化任务队列和互斥锁 ReDim taskQueue(0) mutex = CreateMutex() ' 创建线程 Dim threadId As Integer threadId = CreateThread(AddressOf ThreadFunc) ' 添加任务任务队列 Lock mutex taskQueue(UBound(taskQueue) + 1) = "Task 1" taskQueue(UBound(taskQueue) + 1) = "Task 2" Unlock mutex ' 等待一段时间,让线程执行任务 Sleep 1000 ' 结束线程 TerminateThread threadId ' 销毁互斥锁 DestroyMutex mutex End Sub ``` 以上代码中,我们使用了一个数组作为任务队列,并使用互斥锁来保证线程安全。主程序中创建了一个线程,并向任务队列中添加了两个任务。线程会循环地从任务队列中取出任务并执行,直到任务队列为空。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值