java创建多线程的两种方式和同步

    xiaoxiao2022-07-14  177

    package com.javabase.p1; public class Test_thread { //主程序 public static void main(String[] args) throws InterruptedException { //第一种 MyThread_test1(); System.out.println("============================"); //第二种 //使用synchronized关键字同步run方法 MyThread_testrun(); // 程序暂停5秒 Thread.sleep(1000 * 5); } /** * 创建线程 第二种方式 */ public static void MyThread_testrun() { //自定的类分配数组空间 MyRun[] rThread = new MyRun[10]; //创建线程 for (int i = 0; i < 10; i++) { rThread[i] = new MyRun(); //传入run方法到Thread类的实例对象中 Thread t = new Thread(rThread[i]); //启动线程 t.start(); } } /** * 通过Thread类来创建线程 第一种方式 * @throws InterruptedException */ public static void MyThread_test1() throws InterruptedException { // 线程数组 MyThread[] t = new MyThread[10]; // 创建10个线程 for (int i = 0; i < 10; i++) { t[i] = new MyThread(); } // 启动线程 for (int i = 0; i < t.length; i++) { t[i].start(); t[i].join(); // 让“主线程”等待“子线程”结束之后才能继续运行 } } } /** * 通过继承Thread类来创建线程 * 继承Thread类 自定义类 * */ class MyThread extends Thread { //重写run方法,创建线程会自动调用run方法 @Override public void run() { System.out.println("通过Thread类创建线程" + this.getName()); //获取线程名 } } //通过Runnable接口实现run方法来创建线程 第二种方式 class MyRun implements Runnable{ private static int i = 0; private synchronized void sMethod_inc() { i++; } public synchronized int getI() { return i; } //synchronized关键字同步run方法 @Override public synchronized void run() { sMethod_inc(); System.out.println("通过Runnable接口创建线程" + Thread.currentThread().getName() + "---数字: " + getI() ); //获取线程名 } }
    最新回复(0)