关于java100个线程的信息

博主:adminadmin 2023-03-20 16:11:09 250

今天给各位分享java100个线程的知识,其中也会对进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

Java 如何创建100个Thread 线程

有两种创建线程的方法:一是实现runnable接口,然后将它传递给thread的构造函数,创建一个thread对象;二是直接继承thread类。

java中如何1s钟开启100个线程

让你开启线程的那个主线程休眠1秒:

for(int i=1;i=100;i++)

{

new Thread(testThread).start();

}

Thread.sleep(1000);

java如何用100个线程跑35000次任务

真会玩,跑35000次任务,电脑都被你玩坏。

可以定义一个线程池,将任务平均分配出去。

一个方法单独调用需要0.1秒 开100个线程同时调用需要多长时间

其实多线程的运行,在你这个场景看起来,瓶颈是在CPU上面.

但是现在的cpu都挺好了,跑起来可以达标的.

以下是我测试的程序

import java.util.concurrent.CountDownLatch;

public class AllIn {

private static int threadNum = 100;

private static CountDownLatch latch = new CountDownLatch(threadNum);

public static void main(String[] args) {

long start = System.currentTimeMillis();

for (int index = 0; index  threadNum; index++) {

new Thread(new MyTask("t" + index)).start();

}

try {

latch.await();

} catch (Exception e) {

e.printStackTrace();

}

long end = System.currentTimeMillis();

System.out.println("Threads[" + threadNum + "] is done, spend: " + (end - start) + " mills");

}

static class MyTask implements Runnable {

private String threadName;

public MyTask(String threadName) {

this.threadName = threadName;

}

@Override

public void run() {

try {

Thread.sleep(100);

} catch (Exception e) {

e.printStackTrace();

}

System.out.println(threadName + " is done");

latch.countDown();

}

}

}

测试结果

Threads[100] is done, spend: 150 mills

java创建10个线程,每个线程循环100变,累加AtomicInteger类型变量,将结果打印输出

package com.hellojava;

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

public class Demo {

public static void main(String[] args) {

ScheduledExecutorService execute=Executors.newScheduledThreadPool(10);

for(int i=0;i10;i++) {

execute.scheduleAtFixedRate(new AtomicInteger(), 0, 1, TimeUnit.SECONDS);

}

}

}

class AtomicInteger extends Thread {

private static int count=0;

public void run() {

int i=0;

while (i100) {

count++;

System.out.println(count);

i++;

}

this.stop();

this.destroy();

}

}

java 线程同步求和(100分)

// 你看看吧。。。 不懂的在问我

public class Test implements Runnable {

public static void main(String[] args) {

for (int i = 0; i 100; i++) { // 创建100个线程

Test line = new Test();

Thread t = new Thread(line, i + "");

t.start();

}

}

public void run() { // 线程

for (int i = 0; i 10; i++) { //每条线程输出的次数 如果你是10次 100个线程,如果同步,sum 应该是1000

try {

sum.list();

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

class sum {

static Integer sum = 0;

public synchronized static void list() { //synchronized 代表线程同步, 如果去掉.就会不同步

sum++;

System.out.println("我是线程" + Thread.currentThread().getName()

+ " sum---------" + sum);

}

}

关于java100个线程和的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。