多线程:

(一)进程与线程

进程特点

Java学习之多线程

 

 

 

 

并发与并行的区别:

Java学习之多线程

       

 

 

多线程编程的好处:

                    Java学习之多线程

 

 

 

(二)多线程的建立

1,通过继承Thread类,代码如下:

class MyThread extends Thread {
    private static int K = 10;//类共享变量
    private int M=10;//成员共享变量
    MyThread(){
        super();
    }
    @Override
    public void run() {
        System.out.println("in MyThread run");
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "K:" + K--);
            System.out.println(Thread.currentThread().getName() + "M:" + M--);
        }
    }
}
public class ThreadDemo1 {
    public static void main(String[] args) {
       //多线程Thead方式1
        MyThread thread2 = new MyThread();
        new Thread(thread2,"t2").start();//此时成员变量被共享,静态也被共享,k和M的结果为-9
        new Thread(thread2,"t3").start();
      //多线程Thead方式1
        MyThread thread3=new MyThread();//此时静态类变量被共享,k为-9,M为0.
        thread2.start();
        thread3.start();
    }
}

2,通过实现Runnable接口(推荐),代码如下:

public class ThreadDemo1 {
    public static void main(String[] args) {
         //RUNNABLE 方式2
        MyRunnable myRunnable = new MyRunnable();
        new Thread(myRunnable,"t1").start();//此时成员变量被共享,静态也被共享,K和M为-9
        //RUNNABLE 方式2
        new Thread(myRunnable,"t3").start();
        MyRunnable myRunnable1 = new MyRunnable();//此时成员变量不被共享,静态被共享,K为-9,M为0
        new Thread(myRunnable,"t1").start();
        new Thread(myRunnable1,"t3").start();
    }
}
class MyRunnable implements Runnable {
    private  static int K = 10;
    private  int M = 10;
    @Override
    public void run() {
        System.out.println("in MyRunnable run");
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + " K:" + (K--));
            System.out.println(Thread.currentThread().getName() + " M:" + (M--));
        }
    }
}    

 

3,通过实现Callable接口和Future包装来建立:

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableThread {
    public static void main(String[] args) {
        Callable<Integer> callable = new Callable<Integer>() {
            public Integer call() throws Exception {
                return new Random().nextInt(100);
            }
        };
        FutureTask<Integer> future = new FutureTask<Integer>(callable);
        new Thread(future).start();
        try {
            Thread.sleep(5000);// 可能做一些事情
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-28
  • 2022-12-23
  • 2022-12-23
  • 2021-12-08
  • 2021-08-23
猜你喜欢
  • 2021-09-04
  • 2022-12-23
  • 2021-05-07
  • 2022-02-07
  • 2021-06-28
  • 2022-12-23
相关资源
相似解决方案