多线程的几个小程序,诠释多线程的基本概念

本文介绍了Java中通过实现Runnable接口和继承Thread类两种方式创建多线程的方法,并演示了如何使用Thread.join()确保主线程等待子线程完成,以及如何在多线程环境中传递参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过实现Runnable来实现多线程:
public class TestThread1{
	public static void main(String[] args){
		Runner1 r = new Runner1();
		Thread t = new Thread(r);
		t.start();
//注意:t.run(); 是指方法调用,先执行Runner1()后,再往下执行。
		for(int i=200; i<300; i++){
			System.out.println("main--" + i);
		}
	}
}

class Runner1 implements Runnable{
	public void run(){
		for(int i=0; i<100; i++){
			System.out.println("Runner1--" + i);
		}
	}
}


public class Test1 implements Runnable {

	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println("Thread: " + i );
			try {
				Thread.sleep((int)Math.random() * 200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}  
		}
	}
	
	public static void main(String[] args) {
		Test1 t1 = new Test1();
		Thread t_1 = new Thread(t1);
		t_1.setName("aaa");
		t_1.start();
		for (int i = 0; i < 10; i++) {
			System.out.println("main: " + i );
			try {
				Thread.sleep((int)Math.random() * 200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}  
		}
	}
}



通过继承Thread来实现多线程:
public class TestThread1{
	public static void main(String[] args){
		Runner1 r = new Runner1();
		r.start();
		for(int i=200; i<300; i++){
			System.out.println("main--" + i);
		}
	}
}

class Runner1 extends Thread{
	public void run(){
		for(int i=0; i<100; i++){
			System.out.println("Runner1--" + i);
		}
	}
}


注意:继承了Thread,那么不用再new Thread来起线程,直接用Runner1.start()即可

通过Thread.join()方法来等待当前线程走完
下面的程序,如果join了,那么n就等于1000

	public static volatile int n = 0;

	public void run() {
		for (int i = 0; i < 10; i++, n++)
			try {
				sleep(3); // 为了使运行结果更随机,延迟3毫秒
			} catch (Exception e) {
			}
	}

	public static void main(String[] args) throws Exception {
		Thread threads[] = new Thread[100];
		for (int i = 0; i < threads.length; i++)
			// 建立100个线程
			threads[i] = new Test4();
		for (int i = 0; i < threads.length; i++)
			// 运行刚才建立的100个线程
			threads[i].start();
		if (args.length > 0){
			for (int i = 0; i < threads.length; i++){
				// 100个线程都执行完后继续
				threads[i].join();
			}
		}
		System.out.println("n=" + Test4.n);
	}


在多线程中如何传递参数:
简单的是通过构造函数和set()来传值
复杂的是通过回调函数传值
下面的代码描述了回调传值的用法:
package com.mhm.test;

public class Test5 extends Thread {

	private Work work;

	
	public Test5(Work work) {
		this.work = work;
	}

	public void run() {
		java.util.Random random = new java.util.Random();
		Data data = new Data();
		int n1 = random.nextInt(1000);
		int n2 = random.nextInt(2000);
		int n3 = random.nextInt(3000);
		work.process(data, n1, n2, n3); // 使用回调函数
		System.out.println(String.valueOf(n1) + "+" + String.valueOf(n2) + "+" + String.valueOf(n3) + "=" + data.value);
	}
	
	public static void main(String[] args) {
		Thread t1 = new Test5(new Work());
		Thread t2 = new Test5(new Work());
		Thread t3 = new Test5(new Work());
		
		t1.start();
		t2.start();
		t3.start();
	}
}

class Data {
	public int value = 0;
}

class Work {
	public void process(Data data, Integer... numbers) {
		for (int n : numbers) {
			data.value += n;
		}
	}
}


这个程序可能会输出"NULL":
因为线程可能还没有赋值就已经syso了。
解决办法是在start()后面加个join();
package com.mhm.test;

public class Test6 extends Thread {
	private String value1;
    private String value2;

    public void run()
    {
        value1 = "通过成员变量返回数据";
        value2 = "通过成员方法返回数据";
    }
    public static void main(String[] args) throws Exception
    {
    	Test6 thread = new Test6();
        thread.start();
        System.out.println("value1:" + thread.value1);
        System.out.println("value2:" + thread.value2);
    }
}

多线程 求质数 返回数组中的最大值 bool isPrime(long x) { if (x <= 1) return false; if (x == 2) return true; for (long i = 2; i <= ceil(sqrt((long double)x));i++) if (x%i == 0) return false; return true; } DWORD WINAPI findPrime(void* p) { long result=0; int l = stc(p)->lower, u = stc(p)->uper; int t_id=GetCurrentThreadId(); for (int i = l; i <= u;i++) if (isPrime(i)) { result++; } DWORD dReturn = WaitForSingleObject(mutex_mul_result_h, INFINITE); mul_result += result; ReleaseMutex(mutex_mul_result_h); //EnterCriticalSection(&gCRITICAL_SECTION_Printf); //printf("%d,%d,%d,%d\n", l, u, result,t_id); //fflush(stdout); //LeaveCriticalSection(&gCRITICAL_SECTION_Printf); return 0; } //dispatcher void dispatch() { DWORD Status; timer tm; tm.start(); //srand(time(NULL)); long step = STEP;//ceil(double(TEST/10)); handlenum = 0; for (int i = 1; i <= TEST;) { i += step; handlenum++; } handle_array=new HANDLE[handlenum]; Thread_id = new DWORD[handlenum ]; arg = new FP_ARG[handlenum]; InitializeCriticalSection(&gCRITICAL_SECTION_Printf); mutex_mul_result_h = CreateMutex(NULL, false, mutex_mul_result); handlenum = 0; for (int i = 1; i <= TEST;) { arg[handlenum].lower = i; arg[handlenum].uper = (i + step-1>TEST) ? TEST : i + step-1; handle_array[handlenum]=(HANDLE)CreateThread(NULL, 0, findPrime, &arg[handlenum], 0, &Thread_id[handlenum]); /*EnterCriticalSection(&gCRITICAL_SECTION_Printf); printf("lower:%d uper:%d thread_id:%d\n", arg[handlenum].lower, arg[handlenum].uper,Thread_id[handlenum]); LeaveCriticalSection(&gCRITICAL_SECTION_Printf);*/ i += step; handlenum++; } tm.stop(); Sleep(1000); printf("there are %d threads\n", handlenum); printf("the multithreads use %f msc\n", tm.read()); } //the number of 1-1000000 Primenumber void s_finePrime() { timer tm; long result = 0; tm.start(); for (int i = 1; i <= TEST; i++) if (isPrime(i)) result++; tm.stop(); printf("Single thread result is %d\n", result); printf("Single thread use %f msc\n", tm.read()); } int _tmain(int argc, _TCHAR* argv[]) { dispatch(); WaitForMultipleObjects(handlenum, handle_array, true, INFINITE);//不起作用 printf("the multithreads reslut is %d\n", mul_result); CloseHandle(mutex_mul_result_h); DeleteCriticalSection(&gCRITICAL_SECTION_Printf); s_finePrime(); system("pause"); return 0; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值