欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java多线程基础

程序员文章站 2022-06-17 23:13:10
目录一、线程二、创建多线程的方式1、继承thread类实现多线程2、实现runnable接口方式实现多线程3、callable接口创建线程三、线程的生命周期与状态四、线程的执行顺序1、定时器2、线程的...

一、线程

什么是线程:

线程是进程的一个实体,是cpu调度和分派的基本单位,它是比进程更小的能独立运行的基本单位。

什么是多线程:

多线程指在单个程序中可以同时运行多个不同的线程执行不同的任务。

二、创建多线程的方式

多线程的创建方式有三种:threadrunnablecallable

1、继承thread类实现多线程

      thread thread = new thread() {
            @override
            public void run() {
                super.run();
                while (true) {
                    try {
                        thread.sleep(500);
                    } catch (interruptedexception e) {
                        e.printstacktrace();
                    }
                    system.out.println("1:" + thread.currentthread().getname());
                    system.out.println("2:" + this.getname());
                }
            }
        };
        thread.start();

2、实现runnable接口方式实现多线程

thread thread1 = new thread(new runnable() {
            @override
            public void run() {
                while (true) {
                    try {
                        thread.sleep(500);
                    } catch (interruptedexception e) {
                        e.printstacktrace();
                    }
                    system.out.println("3:" + thread.currentthread().getname());
                }
            }
        });
        thread1.start();

3、callable接口创建线程

public class callabletest {

    public static void main(string[] args) {
        system.out.println("当前线程是:" + thread.currentthread());
        callable mycallable = new callable() {
            @override
            public integer call() throws exception {
                int i = 0;
                for (; i < 10; i++) {

                }
                //当前线程
                system.out.println("当前线程是:" + thread.currentthread()
                        + ":" + i);
                return i;
            }
        };
        futuretask<integer> fu = new futuretask<integer>(mycallable);
        thread th = new thread(fu, "callable thread");

        th.start();

        //得到返回值
        try {
            system.out.println("返回值是:" + fu.get());

        } catch (exception e) {
            e.printstacktrace();
        }
    }
}

当前线程是:thread[main,5,main]
当前线程是:thread[callable thread,5,main]:10
返回值是:10

总结:

实现runnable接口相比继承thread类有如下优势:

  • 可以避免由于java的单继承特性而带来的局限;
  • 增强程序的健壮性,代码能够被多个线程共享,代码与数据是独立的;
  • 适合多个相同程序代码的线程区处理同一资源的情况。

实现runnable接口和实现callable接口的区别:

  • runnable是自从java1.1就有了,而callable是1.5之后才加上去的
  • callable规定的方法是call() , runnable规定的方法是run()
  • callable的任务执行后可返回值,而runnable的任务是不能返回值是(void)
  • call方法可以抛出异常,run方法不可以
  • 运行callable任务可以拿到一个future对象,表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。通过future对象可以了解任务执行情况,可取消任务的执行,还可获取执行结果。
  • 加入线程池运行,runnable使用executorserviceexecute方法,callable使用submit方法。

三、线程的生命周期与状态

Java多线程基础

四、线程的执行顺序

join线程的运行顺序

原理:

1、定时器

import java.util.timer;
import java.util.timertask;

public class traditionaltimertest {
    public static void main(string[] args) {

//         new timer().schedule(new timertask() {
//             @override
//             public void run() {
//
//                 system.out.println("bombing!");
//             }
//         },10000);

        class mytimbertask extends timertask {
            @override
            public void run() {

                system.out.println("bombing!");
                new timer().schedule(new mytimbertask(), 2000);
            }
        }


        new timer().schedule(new mytimbertask(), 2000);


        int count = 0;
        while (true) {
            system.out.println(count++);
            try {
                thread.sleep(1000);
            } catch (interruptedexception e) {
                e.printstacktrace();
            }

        }
    }
}

0
1
bombing!
2
3
bombing!
4
5
bombing!
6
省略...

2、线程的互斥与同步通信

public class traditionalthreadsynchronized {

    public static void main(string[] args) {

        new traditionalthreadsynchronized().init();
    }

    private void init() {
        final outputer outputer = new outputer();

        new thread(new runnable() {
            @override
            public void run() {

                while (true) {
                    try {
                        thread.sleep(10);
                    } catch (interruptedexception e) {
                        e.printstacktrace();
                    }
                    outputer.output("kpioneer");

                }
            }
        }).start();

//        new thread(new runnable() {
//            @override
//            public void run() {
//
//                while (true) {
//                    try {
//                        thread.sleep(10);
//                    } catch (interruptedexception e) {
//                        e.printstacktrace();
//                    }
//                    outputer.output2("tom");
//
//                }
//            }
//        }).start();

        new thread(new runnable() {
            @override
            public void run() {

                while (true) {
                    try {
                        thread.sleep(10);
                    } catch (interruptedexception e) {
                        e.printstacktrace();
                    }
                    outputer.output3("jack");

                }
            }
        }).start();
    }

  static   class outputer {

        public void output(string name) {

            int len = name.length();

            synchronized (outputer.class) {

                for (int i = 0; i < len; i++) {
                    system.out.print(name.charat(i));
                }
                system.out.println();
            }

        }

        public synchronized void output2(string name) {
            int len = name.length();

            for (int i = 0; i < len; i++) {
                system.out.print(name.charat(i));
            }
            system.out.println();
        }

      public static synchronized void output3(string name) {
          int len = name.length();

          for (int i = 0; i < len; i++) {
              system.out.print(name.charat(i));
          }
          system.out.println();
      }
    }
}

3、线程同步通信技术

子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,接着再回到主线程有循环100,如此循环50次,请写出程序。

public class traditionalthreadcommunication {
    public static void main(string[] args) {

        final business business = new business();
        new thread(new runnable() {
                    @override
                    public void run() {
                        for (int i = 1; i <= 50; i++) {
                            business.sub(i);
                        }
                    }
                }
        ).start();
        for (int i = 1; i <= 50; i++) {
            business.main(i);
        }
    }

}

/**
 *要用到共同数据(包括同步锁)的若干方法应该归在同一个类身上,
 * 这种设计正好体现了高类聚和和程序的健壮性
 */
class business {
    private boolean bshouldsub = true;
    public synchronized void sub(int i) {
        if(!bshouldsub) {

            try {
                this.wait();
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
        }
        for (int j = 1; j <= 10; j++) {
            system.out.println("sub thread sequece of " + j + ",loop of " + i);

        }
        bshouldsub = false;
        this.notify();
    }

    public synchronized void main(int i) {
        if(bshouldsub) {
            try {
                this.wait();
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
        }
        for (int j = 1; j <=100; j++) {
            system.out.println("main thread sequece of " + j + ",loop of " + i);

        }
        bshouldsub = true;
        this.notify();
    }
}

sub thread sequece of 1,loop of 1
sub thread sequece of 2,loop of 1
sub thread sequece of 3,loop of 1
sub thread sequece of 4,loop of 1
sub thread sequece of 5,loop of 1
sub thread sequece of 6,loop of 1
sub thread sequece of 7,loop of 1
sub thread sequece of 8,loop of 1
sub thread sequece of 9,loop of 1
sub thread sequece of 10,loop of 1
main thread sequece of 1,loop of 1
main thread sequece of 2,loop of 1
main thread sequece of 3,loop of 1
main thread sequece of 4,loop of 1
main thread sequece of 5,loop of 1
main thread sequece of 6,loop of 1
main thread sequece of 7,loop of 1
main thread sequece of 8,loop of 1
main thread sequece of 9,loop of 1
main thread sequece of 10,loop of 1
main thread sequece of 11,loop of 1
省略中间...
main thread sequece of 99,loop of 1
main thread sequece of 100,loop of 1
sub thread sequece of 1,loop of 2
sub thread sequece of 2,loop of 2
sub thread sequece of 3,loop of 2
sub thread sequece of 4,loop of 2
sub thread sequece of 5,loop of 2
sub thread sequece of 6,loop of 2
sub thread sequece of 7,loop of 2
sub thread sequece of 8,loop of 2
sub thread sequece of 9,loop of 2
sub thread sequece of 10,loop of 2
main thread sequece of 1,loop of 2
main thread sequece of 2,loop of 2
main thread sequece of 3,loop of 2
省略...

到此这篇关于java多线程基础的文章就介绍到这了,更多相关java多线程内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: Java 多线程