java 多线程学习笔记1

来源:互联网 发布:如何淘宝开企业店铺 编辑:程序博客网 时间:2024/03/28 21:09
创建多线程的两种方式,如下
package com.xl.demo;public class TraditionalThread {public static void main(String[] args) {//创建线程方式1Thread thread = new Thread() {@Overridepublic void run() {// 改写父类的run方法while (true) {try {Thread.sleep(5000);System.out.println("th 1"+ Thread.currentThread().getName());System.out.println("th 2" + this.getName());} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}};thread.start();//创建线程方式2 使用Run那边了接口Thread thread2 = new Thread(new Runnable(){@Overridepublic void run() {while (true) {try {Thread.sleep(5000);System.out.println("th 1"+ Thread.currentThread().getName());} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}});thread2.start();/** *  下面的程序将执行Thread子类的run方法,只有在没有重写Thread的run方法时,才会执行Runable中的run方法 */new Thread(new Runnable(){public void run() {while (true) {try {Thread.sleep(5000);System.out.println("Runnable run method "+ Thread.currentThread().getName());} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}){public void run() {while (true) {try {Thread.sleep(5000);System.out.println("Thread run method "+ Thread.currentThread().getName());} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}.start();}}


0 0
原创粉丝点击