写给自己的JAVA工程师之路-多线程

来源:互联网 发布:社会法则 知乎 编辑:程序博客网 时间:2024/06/06 09:40

1 进程与线程

在每一个进程上可以继续划分多个线程,那么线程的操作一定比进程要快,所以多线程的操作性能一定是要超过多进程的操作性能,但是所有的线程都一定是要在进程的基础上进行划分。所以进程一旦消失,线程一定会消失。

线程永远要依附于进程的存在。

2 多线程的三种实现方式

class MyThread extends Thread{private int count = 5;public void run(){for(int i=1;i<=5;i++){if(count>0)System.out.println("count = "+count--);}}}public class demo {public static void main(String[] args) {MyThread mt1 = new MyThread();MyThread mt2 = new MyThread();MyThread mt3 = new MyThread();mt1.start();mt2.start();mt3.start();}}
class MyThread1 implements Runnable{private int count = 5;@Overridepublic void run(){for(int i=1;i<=50;i++){if(this.count>0)System.out.println("count = "+this.count --);}}}public class demo1 {public static void main(String[] args) {MyThread1 mt1 = new MyThread1();new Thread(mt1).start();new Thread(mt1).start();new Thread(mt1).start();//new Thread(new Runnable() {////@Override//public void run() {//// TODO Auto-generated method stub//for(int i=1;i<=10;i++){//System.out.println(i);//}//}//}).start();}}

class MyThread2 implements Callable<String>{private int count = 5;@Overridepublic String call(){for(int i=1;i<=50;i++){if(this.count>0)System.out.println("count = "+this.count --);}return "数完了";}}public class demo2 {public static void main(String[] args) throws InterruptedException, ExecutionException {Callable<String> cal = new MyThread2();FutureTask<String> task = new FutureTask<String>(cal);Thread thread = new Thread(task);thread.start();System.out.println(task.get());}}

如果说第二种是红花,那么其余两种就是绿叶!

第一种和第二种的区别:

多线程需要一个主类,这个类要么继承Thread类,要么实现Runnable接口

使用Runnable接口可以比Thread类更好的实现数据共享操作,并且利用Runnable接口可以避免单继承局限






原创粉丝点击