导航:首页 > 编程语言 > threadsjava

threadsjava

发布时间:2022-07-11 19:11:06

java线程传值的问题

把那些对象类型的变量定义为 static 类型

或者,有一个线程间传值得方法,管道技术,不知道你有没有接触这方面的内容:
Java中利用管道实现线程间的通讯
管道(pipe)流是一种特殊的流,用于在不同线程(threads)间直接传送数据。一个线程发送数据到输出管道,另一个线程从输入管道中读数据。通过使用管道,实现不同线程间的通讯。
你可以搜艘县官的内容,相信对你有帮助

❷ Java 如何创建100个Thread 线程

“创建100个线程”和“创建1个线程”是一样的。
(如果不一样,只可能是你问得唐突、不清晰)
你可以把100个线程放到一个数组中。
Thread threads[]=new Thread[100];
//然后逐个生成启动
for(int i=0;i<100;i++){
threads[i]=new Thread(//put some runnable here );
threads[i].start();
}

❸ 如何用Java编写多线程

在java中要想实现多线程,有两种手段,一种是继续Thread类,另外一种是实现Runable接口。
对于直接继承Thread的类来说,代码大致框架是:
?
123456789101112 class 类名 extends Thread{ 方法1; 方法2; … public void run(){ // other code… } 属性1; 属性2; … }
先看一个简单的例子:
?
/** * @author Rollen-Holt 继承Thread类,直接调用run方法 * */class hello extends Thread { public hello() { } public hello(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + "运行 " + i); } } public static void main(String[] args) { hello h1=new hello("A"); hello h2=new hello("B"); h1.run(); h2.run(); } private String name; }
【运行结果】:
A运行 0
A运行 1
A运行 2
A运行 3
A运行 4
B运行 0
B运行 1
B运行 2
B运行 3
B运行 4
我们会发现这些都是顺序执行的,说明我们的调用方法不对,应该调用的是start()方法。
当我们把上面的主函数修改为如下所示的时候:
?
123456 public static void main(String[] args) { hello h1=new hello("A"); hello h2=new hello("B"); h1.start(); h2.start(); }
然后运行程序,输出的可能的结果如下:
A运行 0
B运行 0
B运行 1
B运行 2
B运行 3
B运行 4
A运行 1
A运行 2
A运行 3
A运行 4
因为需要用到CPU的资源,所以每次的运行结果基本是都不一样的,呵呵。
注意:虽然我们在这里调用的是start()方法,但是实际上调用的还是run()方法的主体。
那么:为什么我们不能直接调用run()方法呢?
我的理解是:线程的运行需要本地操作系统的支持。
如果你查看start的源代码的时候,会发现:
?
1234567891011121314151617 public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus != 0 || this != me) throw new IllegalThreadStateException(); group.add(this); start0(); if (stopBeforeStart) { stop0(throwableFromStop); } } private native void start0();
注意我用红色加粗的那一条语句,说明此处调用的是start0()。并且这个这个方法用了native关键字,次关键字表示调用本地操作系统的函数。因为多线程的实现需要本地操作系统的支持。
但是start方法重复调用的话,会出现java.lang.IllegalThreadStateException异常。
通过实现Runnable接口:

大致框架是:
?
123456789101112 class 类名 implements Runnable{ 方法1; 方法2; … public void run(){ // other code… } 属性1; 属性2; … }

来先看一个小例子吧:
?
2930 /** * @author Rollen-Holt 实现Runnable接口 * */class hello implements Runnable { public hello() { } public hello(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + "运行 " + i); } } public static void main(String[] args) { hello h1=new hello("线程A"); Thread demo= new Thread(h1); hello h2=new hello("线程B"); Thread demo1=new Thread(h2); demo.start(); demo1.start(); } private String name; }
【可能的运行结果】:
线程A运行 0
线程B运行 0
线程B运行 1
线程B运行 2
线程B运行 3
线程B运行 4
线程A运行 1
线程A运行 2
线程A运行 3
线程A运行 4

关于选择继承Thread还是实现Runnable接口?
其实Thread也是实现Runnable接口的:
?
12345678 class Thread implements Runnable { //… public void run() { if (target != null) { target.run(); } } }
其实Thread中的run方法调用的是Runnable接口的run方法。不知道大家发现没有,Thread和Runnable都实现了run方法,这种操作模式其实就是代理模式。关于代理模式,我曾经写过一个小例子呵呵,大家有兴趣的话可以看一下:http://www.cnblogs.com/rollenholt/archive/2011/08/18/2144847.html
Thread和Runnable的区别:
如果一个类继承Thread,则不适合资源共享。但是如果实现了Runable接口的话,则很容易的实现资源共享。
?
/** * @author Rollen-Holt 继承Thread类,不能资源共享 * */class hello extends Thread { public void run() { for (int i = 0; i < 7; i++) { if (count > 0) { System.out.println("count= " + count--); } } } public static void main(String[] args) { hello h1 = new hello(); hello h2 = new hello(); hello h3 = new hello(); h1.start(); h2.start(); h3.start(); } private int count = 5; }

【运行结果】:
count= 5
count= 4
count= 3
count= 2
count= 1
count= 5
count= 4
count= 3
count= 2
count= 1
count= 5
count= 4
count= 3
count= 2
count= 1
大家可以想象,如果这个是一个买票系统的话,如果count表示的是车票的数量的话,说明并没有实现资源的共享。
我们换为Runnable接口:
?
12345678910111213141516171819 /** * @author Rollen-Holt 继承Thread类,不能资源共享 * */class hello implements Runnable { public void run() { for (int i = 0; i < 7; i++) { if (count > 0) { System.out.println("count= " + count--); } } } public static void main(String[] args) { hello he=new hello(); new Thread(he).start(); } private int count = 5; }

【运行结果】:
count= 5
count= 4
count= 3
count= 2
count= 1

总结一下吧:
实现Runnable接口比继承Thread类所具有的优势:
1):适合多个相同的程序代码的线程去处理同一个资源
2):可以避免java中的单继承的限制
3):增加程序的健壮性,代码可以被多个线程共享,代码和数据独立。

所以,本人建议大家劲量实现接口。
?

❹ java 根据线程名字查询一个线程,能实现吗

根据线程名称找到线程,在java中是可以实现的,实现步骤是:
1、首先获取Java VM中当前运行的所有线程
以下代码是用数组返回Java VM中当前运行的所有线程


publicstaticThread[]findAllThreads()
{
ThreadGroupgroup=Thread.currentThread().getThreadGroup();
ThreadGrouptopGroup=group;

/*遍历线程组树,获取根线程组*/
while(group!=null)
{
topGroup=group;
group=group.getParent();
}
/*激活的线程数加倍*/
intestimatedSize=topGroup.activeCount()*2;
Thread[]slackList=newThread[estimatedSize];

/*获取根线程组的所有线程*/
intactualSize=topGroup.enumerate(slackList);
/*intoalistthatistheexactsize*/
Thread[]list=newThread[actualSize];
System.array(slackList,0,list,0,actualSize);
return(list);
}

2、遍历线程,比对名称,找到需要寻找的线程
以下代码可得到线程的名称

Stringname=thread.getName();

❺ 怎样分析 JAVA 的 Thread Dumps

当有障碍,或者是一个基于 JAVA 的 WEB 应用运行的比预期慢的时候,我们需要使用 thread mps。如果对于你来说,thread mps 是非常复杂的,这篇文章或许能对你有所帮助。在这里我将解释在 JAVA 中什么是 threads,他们的类型,怎么被创建的,怎样管理它们,你怎样从正在运行的应用中 mp threads,最后你可以怎样分析它以及确定瓶颈或者是阻塞线程。本文来自于 JAVA 应用程序长期调试经验的结果。


Java and Thread

一个 web 服务器使用几十到几百个线程来处理大量并发用户,如果一个或多个线程使用相同的资源,线程之间的竞争就不可避免了,并且有时候可能会发生死锁。


Thread contention 是一个线程等待锁的一个状态,这个锁被另外一个线程持有,等待被释放,不同的线程频繁访问 WEB 应用的共享资源。例如,记录一条日志,线程尝试记录日志之前必须先获取锁来访问共享资源。


死锁是线程竞争的一个特殊状态,一个或是多个线程在等待其他线程完成它们的任务为了完成它们自己的任务。


线程竞争会引起各种不同的问题,为了分析这些这些问题,你需要使用 mp threads,mp threads 能给你提供每个线程的精确状态信息。


JAVA 线程的背景资料

线程同步

一个线程可以与其他线程在同一时间内被处理。为了确保一致性,当多个线程试图使用共享资源的时候,通过使用 hread synchronization 在同一时间内,应该只有一个线程能访问共享资源


JAVA 中的线程同步可以使用监视器,每个 JAVA 对象都有一个单独的监视器,这个监视器仅仅只能被一个线程拥有,对于拥有一个由不同的线程所拥有的监视器的线程,确实需要在队列中等待,以便其他线程释放它的监视器。


线程状态

为了分析一个 thread mp 文件,你需要知道线程状态。线程情况在 java.lang.Thread.State 中阐明了。

当使用 java.lang.Thread 对象创建线程的时候,线程被命名为 Thread-(Number) 。当使用 java.util.concurrent.DefaultThreadFactory 对象创建线程的时候,线程被命名为 named pool-(Number)-thread-(Number)。当为应用程序分析成百上千的线程的时候,如果线程依然用它们默认的名字,分析它们将变得非常困难,因为这是非常难以辨别这些线程来分析的。


因此,你被建议开发一个命名线程的规则当一个新线程被创建的时候。


当你使用 java.lang.Thread 创建线程,你可以通过创建参数给该线程定义个约定俗成的名字。


public Thread(Runnable target, String name);

public Thread(ThreadGroup group, String name);

public Thread(ThreadGroup group, Runnable target, String name);

public Thread(ThreadGroup group, Runnable target, String name, long stackSize);

当你使用 java.util.concurrent.ThreadFactory 创建线程的时候,你可以通过生成你自己的线程工厂来命名它,如果你不需要特别的功能性,你可以使用 MyThreadFactory 作为以下描述:


import java.util.concurrent.ConcurrentHashMap;

import java.util.concurrent.ThreadFactory;

import java.util.concurrent.atomic.AtomicInteger;


public class MyThreadFactory implements ThreadFactory {

private static final ConcurrentHashMap<String, AtomicInteger> POOL_NUMBER =

new ConcurrentHashMap<String, AtomicInteger>();

private final ThreadGroup group;

private final AtomicInteger threadNumber = new AtomicInteger(1);

private final String namePrefix;


public MyThreadFactory(String threadPoolName) {


if (threadPoolName == null) {

throw new NullPointerException("threadPoolName");

}

POOL_NUMBER.putIfAbsent(threadPoolName, new AtomicInteger());


SecurityManager securityManager = System.getSecurityManager();

group = (securityManager != null) ? securityManager.getThreadGroup() :

Thread.currentThread().getThreadGroup();


AtomicInteger poolCount = POOL_NUMBER.get(threadPoolName);


if (poolCount == null) {

namePrefix = threadPoolName + " pool-00-thread-";

} else {

namePrefix = threadPoolName + " pool-" + poolCount.getAndIncrement() + "-thread-";

}

}


public Thread newThread(Runnable runnable) {

Thread thread = new Thread(group, runnable, namePrefix + threadNumber.getAndIncrement(), 0);


if (thread.isDaemon()) {

thread.setDaemon(false);

}


if (thread.getPriority() != Thread.NORM_PRIORITY) {

thread.setPriority(Thread.NORM_PRIORITY);

}


return thread;

}

}

使用 MBean 获取更多的细节信息

你可以使用 MBean 来获取 ThreadInfo 对象。你也可以获取更加多通过 thread mps 不能获取的信息。通过使用 ThreadInfo。


ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();

long[] threadIds = mxBean.getAllThreadIds();

ThreadInfo[] threadInfos =

mxBean.getThreadInfo(threadIds);


for (ThreadInfo threadInfo : threadInfos) {

System.out.println(

threadInfo.getThreadName());

System.out.println(

threadInfo.getBlockedCount());

System.out.println(

threadInfo.getBlockedTime());

System.out.println(

threadInfo.getWaitedCount());

System.out.println(

threadInfo.getWaitedTime());

}

你可以使用方法 ThreadInfo 来提取阻塞线程或者是等待线程花费的时间。并利用这一点,你也可以得到那些处于非活动状态的时间异常长的线程列表。

❻ java线程与操作系统线程

java线程管理是JVM的一部分,虽然大部分JVM直接映射java线程到底层系统线程,但是还是java的线程管理决定谁有机会运行
The thread scheler is the part of the JVM (although most JVMs map Java threads directly to native threads on the underlying OS) that decides which thread should run at any given moment, and also takes threads out of the run state. Assuming a single processor machine, only one thread can actually run at a time. Only one stack can ever be executing at one time. And it's the thread scheler that decides which thread—of all that are eligible—will actually run.

❼ java中Thread类有哪些主要成员变量

classThreadimplementsRunnable{
/*<clinit>does.*/
();
static{
registerNatives();
}

privatecharname[];
privateintpriority;
privateThreadthreadQ;
privatelongeetop;
privatebooleanstarted;//

/*Whetherornottosingle_stepthisthread.*/
privatebooleansingle_step;

/*.*/
privatebooleandaemon=false;

/*.*/
privatebooleanstillborn=false;

/*Whatwillberun.*/
privateRunnabletarget;

/*Thegroupofthisthread*/
privateThreadGroupgroup;

/**/
;

/**/
;

/*.*/
;
/*.Thismapismaintained
*bytheThreadLocalclass.*/
ThreadLocal.ThreadLocalMapthreadLocals=null;

/*
*Inheritable.Thismapis
*.
*/
ThreadLocal.=null;

/*
*,or0ifthecreatordid
*notspecifyastacksize.ItisuptotheVMtodowhateverit
*likeswiththisnumber;someVMswillignoreit.
*/
privatelongstackSize;

/*
*ThreadID
*/
privatelongtid;

/*ForgeneratingthreadID*/
;

/*Javathreadstatusfortools,
*initializedtoindicatethread'notyetstarted'
*/
privateintthreadStatus=0;


(){
return++threadSeqNumber;
}

/*/O
*operation,ifany.Theblocker'
*aftersettingthisthread'sinterruptstatus.
*/
;
privateObjectblockerLock=newObject();

/*Settheblockerfield;invokedviasun.misc.SharedSecretsfromjava.niocode
*/
voidblockedOn(Interruptibleb){
synchronized(blockerLock){
blocker=b;
}
}

/**
*.
*/
publicfinalstaticintMIN_PRIORITY=1;

/**
*.
*/
publicfinalstaticintNORM_PRIORITY=5;

/**
*.
*/
publicfinalstaticintMAX_PRIORITY=10;

❽ Java线程 Java线程

Java Thread sleep示例
这里是一个简单的程序,它使用Thread.sleep()暂停主线程2分钟。
[java] view plain
package com.journaldev.threads;
public class ThreadSleep {
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(2000);
System.out.println("Sleep time in ms = "+(System.currentTimeMillis()-start));

}
}
如果你将执行上面的程序,你将注意到线程休眠打印时间略微大于2000毫秒,导致线程这样执行的原因是操作系统具体实现和线程调度引起的。
Java线程休眠要点:
1.它总是暂停当前执行的线程
2.实际休眠的线程在唤醒开始执行前依赖于系统定时器和调度器,对于一个平稳的系统来住,线程实际执行的时间接近于指定线程休眠时间,但是对于一个忙碌的系统来说它将稍微超出一些。
3.当线程休眠时不会丢失已经获得的监控和锁。
4.任何线程都能中断当前休眠的线程,将导致InterruptedException异常抛出。
线程休眠是如何工作的:
Thread.sleep()与线程调度器交互,在指定的时间内将当前线程作为等待状态放入,一旦等待时间结束后,线程状态变为可运行状态,并等待CPU进一步执行。所以当前线程的实际休眠时间依赖于线程调度器和一部门操作系统。

❾ java fork join和thread的区别

Java并发编程的4种风格:Threads,Executors,ForkJoin和Actors
我们生活在一个事情并行发生的世界。自然地,我们编写的程序也反映了这个特点,它们可以并发的执行。当然除了Python代码(译者注:链接里面讲述了Python的全局解释器锁,解释了原因),不过你仍然可以使用Jython在JVM上运行你的程序,来利用多处理器电脑的强大能力。
然而,并发程序的复杂程度远远超出了人类大脑的处理能力。相比较而言,我们简直弱爆了:我们生来就不是为了思考多线程程序、评估并发访问有限资源以及预测哪里会发生错误或者瓶颈。
面对这些困难,人类已经总结了不少并发计算的解决方案和模型。这些模型强调问题的不同部分,当我们实现并行计算时,可以根据问题做出不同的选择。
在这篇文章中,我将会用对同一个问题,用不同的代码来实现并发的解决方案;然后讨论这些方案有哪些好的地方,有哪些缺陷,可能会有什么样的陷阱在等着你。
我们将介绍下面几种并发处理和异步代码的方式:
• 裸线程
• Executors和Services
• ForkJoin框架和并行流
• Actor模型
为了更加有趣一些,我没有仅仅通过一些代码来说明这些方法,而是使用了一个共同的任务,因此每一节中的代码差不多都是等价的。另外,这些代码仅仅是展示用的,初始化的代码并没有写出来,并且它们也不是产品级的软件示例。
对了,最后一件事:在文章最后,有一个小调查,关于你或者你的组织正在使用哪种并发模式。为了你的工程师同胞们,请填一下调查!
任务
任务:实现一个方法,它接收一条消息和一组字符串作为参数,这些字符串与某个搜索引擎的查询页面对应。对每个字符串,这个方法发出一个http请求来查询消息,并返回第一条可用的结果,越快越好。
如果有错误发生,抛出一个异常或者返回空都是可以的。我只是尝试避免为了等待结果而出现无限循环。
简单说明:这次我不会真正深入到多线程如何通讯的细节,或者深入到Java内存模型。如果你迫切地想了解这些,你可以看我前面的文章利用JCStress测试并发。
那么,让我们从最直接、最核心的方式来在JVM上实现并发:手动管理裸线程。
方法1:使用“原汁原味”的裸线程
解放你的代码,回归自然,使用裸线程!线程是并发最基本的单元。Java线程本质上被映射到操作系统线程,并且每个线程对象对应着一个计算机底层线程。
自然地,JVM管理着线程的生存期,而且只要你不需要线程间通讯,你也不需要关注线程调度。
每个线程有自己的栈空间,它占用了JVM进程空间的指定一部分。
线程的接口相当简明,你只需要提供一个Runnable,调用.start()开始计算。没有现成的API来结束线程,你需要自己来实现,通过类似boolean类型的标记来通讯。

阅读全文

与threadsjava相关的资料

热点内容
androidgradle配置签名 浏览:92
文件夹左边的空心三角符号是什么 浏览:281
app英语音频试卷扫码怎么听 浏览:610
字符串编译预处理 浏览:699
苹果手机怎么会显示多个App 浏览:237
不去互联网程序员 浏览:552
电脑qq邮箱解压的图片保存在哪里 浏览:544
嵌入命令行 浏览:91
档案为什么被加密 浏览:486
十天学会单片机13 浏览:875
荣耀怎么设置让app一直运行 浏览:993
共享文件夹能在哪里找到 浏览:435
旅游订旅店用什么app 浏览:240
一个女程序员的声音 浏览:496
魔术app怎么用 浏览:340
单片机有4个8位的io口 浏览:897
win10rar解压缩软件 浏览:169
plc教程pdf 浏览:668
pythonshell清屏命令 浏览:281
检测到加密狗注册服务器失败 浏览:205