zoukankan      html  css  js  c++  java
  • Java多线程编程初识

      每个正在系统上运行的程序都是一个进程。每个进程包含一到多个线程。进程也可能是整个程序或者是部分程序的动态执行。线程是一组指令的集合,或者是程序的特殊段,它可以在程序里独立执行。也可以把它理解为代码运行的上下文。所以线程基本上是轻量级的进程,它负责在单个程序里执行多任务。通常由操作系统负责多个线程的调度和执行。

      Java对多线程的支持是非常强大的,他屏蔽掉了许多的技术细节,让我们可以轻松的开发多线程的应用程序。

      Java里面实现多线程,有2个方法:

      1.继承 Thread类

      public class TestThread extends Thread{
        //重写run方法
        public void run(){
          Thread th=Thread.currentThread();
          for(int i=0;i<100;i++){
            try {
              Thread.sleep(500);
            } catch (InterruptedException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
            System.out.println(th.getName()+":"+i);
          }
        }
        public static void main(String[] args) {
          //启动子线程
          TestThread tt=new TestThread();
          tt.start();

          //当前的线程对象
          Thread mainThread=Thread.currentThread();
          for(int i=0;i<100;i++){
            try {
              mainThread.sleep(500);
            } catch (InterruptedException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
            System.out.println(mainThread.getName()+":"+i);
          }
        }
      }

      2.实现 Runnable接口

      public class TestRunnable implements Runnable{
        private Thread th;
        public TestRunnable(){
          th=new Thread(this);
          th.start();
        }
        public void run() {
          // TODO Auto-generated method stub
          for(int i=0;i<10;i++){
            try {
              Thread.sleep(500);
            } catch (InterruptedException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+":"+i);
          }
        }
        public static void main(String[] args) {
          TestRunnable runnable=new TestRunnable();
        }
      }

  • 相关阅读:
    setBackgroundResource和setImageResource的区别
    startActivityForResult 请求码不正确
    startActivityForResult 请求码不正确
    startActivityForResult 请求码不正确
    svn“Previous operation has not finished; run 'cleanup' if it was interrupted“报错的解决方法
    svn“Previous operation has not finished; run 'cleanup' if it was interrupted“报错的解决方法
    svn“Previous operation has not finished; run 'cleanup' if it was interrupted“报错的解决方法
    android stadio svn 使用技巧
    android stadio svn 使用技巧
    android stadio svn 使用技巧
  • 原文地址:https://www.cnblogs.com/leafde/p/3712628.html
Copyright © 2011-2022 走看看