Java多线程之多线程的基本使用

  在总结JDBC数据库连接池的时候,发现Java多线程这块掌握得不是很好,因此回头看了下多线程的内容。做一下多线程模块的学习和总结,稳固一下多线程这块的基础。关于多线程的一些理论知识,这里不想啰嗦太多,可以进行下搜索了解。

1. 如何使用Java创建多线程

  使用Java多线程,总的来说方法有两种:①继承Thread类,重写run方法  ②把相关的类实现Runnable(可运行)接口,重写run方法。③实现Callable接口(相对用得较少)

1 package com.scl.thread; 2 3 public class TestThread 4 { 5 public static void main(String[] args) throws Exception 6 { 7 String mainName = Thread.currentThread().getName(); 8 System.out.println(mainName + "线程开始运行"); 9 10 // 方法1 使用继承对线程进行调用 11 MyThread myThread = new MyThread(); 12 myThread.setName("wft"); 13 myThread.start(); 14 myThread.join(); 15 16 // 方法2 继承Runnable接口进行调用 17 Thread thread = new Thread(new MyRunnable()); 18 thread.start(); 19 20 System.out.println(mainName + "线程结束"); 21 } 23 } 24 25 // 使用runnable开启线程 26 class MyRunnable implements Runnable 27 { 28 @Override 29 public void run() 30 { 31 // 获取调用线程的名字 32 String curName = Thread.currentThread().getName(); 33 System.out.println(curName + "线程启动"); 34 try 35 { 36 Thread.sleep(1000); 37 System.out.println(curName + "正在运行"); 38 } 39 catch (InterruptedException e) 40 { 41 e.printStackTrace(); 42 } 43 System.out.println(curName + "线程结束"); 44 } 45 } 46 47 // 使用Thread进行run方法的编写,开启线程 48 class MyThread extends Thread 49 { 50 // Thread.currentThread()调用这个方法的线程名称。 51 String s = Thread.currentThread().getName(); // 调用这个类的是main方法调用,run方法交由新线程操作 52 53 public MyThread() 54 { 55 System.out.println("Thread.currentThread().getname()=" + Thread.currentThread().getName()); 56 // 线程没运行前初始化的名字.因为类的初始化跟线程运行无关,这里返回的是处世话的名字 57 System.out.println("This.getName=" + this.getName()); 58 } 59 60 @Override 61 public void run() 62 { 63 // run方法交由新线程操作,所以调用的名称不是main 64 String strName = Thread.currentThread().getName(); 65 System.out.println("this.getName " + this.getName()); 66 // main 67 System.out.println("do u no s?" + s); 68 69 System.out.println(strName + " 开始数数"); 70 for (int i = 0; i < 100; i++) 71 { 72 System.out.println(strName + " " + i); 73 } 74 System.out.println(strName + " 数数完毕"); 75 } 76 77 // 返回设置的name 78 public String bName() 79 { 80 return this.getName(); 81 } 82 } 

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/7f1bbc19ba60ab52ac6359c22c1fd403.html