Java:创建线程
Java定义了两种创建线程的方法:
1.实现Runnable接口
要实现Runnable接口,只需简单地实现run()方法即可,声明如下:public void run()
在run()方法中,可以定义构成新线程的代码。需重点理解的是,run()可以调用其它方法、使用其他类和声明变量,就像主线程能做的那样。唯一的区别是:run()方法是程序的另一个并发的执行线程的进入店,这个线程在run()方法返回时结束。
创建新线程以后,直到调用了它的start()方法后才会执行。本质上,start()执行对run()的调用。
// Create a second thread.
public class NewThread implements Runnable{
Thread t;
NewThread(){
t=new Thread(this,"Demo Thread");
System.out.println("Child thread: "+t);
t.start();
} // This is the entry point of the second thread.
public void run(){
try{
for(int i=5;i>0;i--){
System.out.println("Child thread: "+i);
Thread.sleep(500);
}
}
catch(InterruptedException e){
System.out.println("Child thread interrupted");
}
System.out.println("Exiting child thread");
}
} class ThreadDemo{
public static void main(String args[]){
new NewThread();
try{
for(int i=5;i>0;i--){
System.out.println("Main thread: "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e){
System.out.println("Main thread interrupted");
}
System.out.println("Exiting Main thread");
}
}
输出:
Child thread: Thread[Demo Thread,5,main]
Main thread: 5
Child thread: 5
Child thread: 4
Main thread: 4
Child thread: 3
Child thread: 2
Main thread: 3
Child thread: 1
Exiting child thread
Main thread: 2
Main thread: 1
Exiting Main thread
2. 扩展Thread类本身
第二种创建线程的方法是创建一个扩展Thread类的新类,然后创建该类的一个实例。这个扩展的类必须重写run()方法,这是新线程的进入点,同时它也必须调用start()方法来执行线程。
// Create a second thread.
public class NewThread extends Thread{ NewThread(){
super("Demo thread");
System.out.println("Child thread: "+this);
start();
} // This is the entry point of the second thread.
public void run(){
try{
for(int i=5;i>0;i--){
System.out.println("Child thread: "+i);
Thread.sleep(500);
}
}
catch(InterruptedException e){
System.out.println("Child thread interrupted");
}
System.out.println("Exiting child thread");
}
} class ThreadDemo{
public static void main(String args[]){
new NewThread();
try{
for(int i=5;i>0;i--){
System.out.println("Main thread: "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e){
System.out.println("Main thread interrupted");
}
System.out.println("Exiting Main thread");
}
}
输出:
Child thread: Thread[Demo thread,5,main]
Main thread: 5
Child thread: 5
Child thread: 4
Main thread: 4
Child thread: 3
Child thread: 2
Main thread: 3
Child thread: 1
Exiting child thread
Main thread: 2
Main thread: 1
Exiting Main thread
同步:当两个或多个线程需要访问同一共享资源时,需要某种方式来确保资源在某一时刻只被一个线程使用,这个方式称为同步。
不使用同步的例子:
class Callme{
void call(String msg){
System.out.print("["+msg);
try{
Thread.sleep(1000);
}
catch(InterruptedException e){
System.out.println("Interrupted");
}
System.out.println("]");
}
} class Caller implements Runnable{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s){
target=targ;
msg=s;
t=new Thread(this);
t.start();
} public void run(){
target.call(msg);
}
} public class Synch {
public static void main(String args[]){
Callme target=new Callme();
Caller ob1=new Caller(target,"Hello");
Caller ob2=new Caller(target,"Synchronized");
Caller ob3=new Caller(target,"World"); try{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e){
System.out.println("Interrupted");
}
}
}
输出:
[Hello[World[Synchronized]
]
]
使用同步,只需简单地在call()的定义前面加上关键字synchronized即可
class Callme{
synchronized void call(String msg){
输出:
[Hello]
[Synchronized]
[World]
当不能在类相应的方法中添加synchronized关键字时,只需要将对该类方法的访问置于一个synchronized快中
public void run(){
synchronized(target){
target.call(msg);
}
}
Java:创建线程的更多相关文章
- -1-5 java 多线程 概念 进程 线程区别联系 java创建线程方式 线程组 线程池概念 线程安全 同步 同步代码块 Lock锁 sleep()和wait()方法的区别 为什么wait(),notify(),notifyAll()等方法都定义在Object类中
本文关键词: java 多线程 概念 进程 线程区别联系 java创建线程方式 线程组 线程池概念 线程安全 同步 同步代码块 Lock锁 sleep()和wait()方法的区别 为什么wait( ...
- 操作系统实现线程的几种模式 和 java创建线程的3个方式
操作系统实现线程的几种模式 和 java创建线程的3个方式 这是两个概念 在操作系统中,线程可以实现在用户模式下,也可以实现在内核模式下,也可以两者结合实现. 1.实现线程的三种方式: (1)继承t ...
- Java并发编程:Java创建线程的三种方式
目录 引言 创建线程的三种方式 一.继承Thread类 二.实现Runnable接口 三.使用Callable和Future创建线程 三种方式的对比 引言 在日常开发工作中,多线程开发可以说是必备技能 ...
- Java创建线程的三种主要方式
Java创建线程的主要方式 一.继承Thread类创建 通过继承Thread并且重写其run(),run方法中即线程执行任务.创建后的子类通过调用 start() 方法即可执行线程方法. 通过继承Th ...
- Java创建线程的四种方式
Java创建线程的四种方式 1.继承Thread类创建线程 定义Thread类的子类,并重写该类的run方法,run()方法的内容就是该线程执行的内容 创建Thread子类的实例,即创建了线程对象. ...
- 当阿里面试官问我:Java创建线程有几种方式?我就知道问题没那么简单
这是最新的大厂面试系列,还原真实场景,提炼出知识点分享给大家. 点赞再看,养成习惯~ 微信搜索[武哥聊编程],关注这个 Java 菜鸟. 昨天有个小伙伴去阿里面试实习生岗位,面试官问他了一个老生常谈的 ...
- java创建线程的多种方式
java创建线程的四种方式 1.继承 Thread 类 通过继承 Thread 类,并重写它的 run 方法,我们就可以创建一个线程. 首先定义一个类来继承 Thread 类,重写 run 方法. 然 ...
- Java创建线程的细节分析
转载:http://shmilyaw-hotmail-com.iteye.com/blog/1880902 前言 关于线程创建的问题,可以说是老生常谈了.在刚开始学习Thread的时候基本上都会接触到 ...
- java创建线程的三种方法
这里不会贴代码,只是将创建线程的三种方法做个笼统的介绍,再根据源码添加上自己的分析. 通过三种方法可以创建java线程: 1.继承Thread类. 2.实现Runnable接口. 3.实现Callab ...
- java创建线程
创建一个线程 Java提供了两种创建线程方法: 通过实现Runable接口: http://blog.csdn.net/duruiqi_fx/article/details/52187275 通过继承 ...
随机推荐
- jQuery的事件绑定和解除
1 . 绑定事件 语法 : bind(type,data,fn) 描述 : 为每一个匹配的特定元素(像 click)绑定一个事件处理器函数. type(String) : 事件类型 data(Obje ...
- js正則函數 match、exec、test、search、replace、split 使用介紹集合
match 方法 使用正則表達式模式對字元串執行查找,並將包含查找的結果作為數組返回. stringObj.match(rgExp) 參數 stringObj 必選項.對其進行查找的 String 對 ...
- java 创建 HMAC 签名
ava 创建 HMAC 签名 psd素材 1. []ComputopTest.java package com.javaonly.hmac.test; import java.io.IOExcepti ...
- BZOJ 3043 IncDec Sequence:反向差分
题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=3043 题意: 给定一个长度为n的数列a[i],每次可以选择一个区间[l,r],使这个区间内 ...
- codeforces 587B B. Duff in Beach(dp)
题目链接: B. Duff in Beach time limit per test 2 seconds memory limit per test 256 megabytes input stand ...
- P4311 士兵占领[最大流]
题目地址 有一个$M * N$的棋盘,有的格子是障碍.现在你要选择一些格子来放置一些士兵,一个格子里最多可以放置一个士兵,障碍格里不能放置士兵.我们称这些士兵占领了整个棋盘当满足第i行至少放置了$L_ ...
- javacpp-FFmpeg系列之2:通用拉流解码器,支持视频拉流解码并转换为YUV、BGR24或RGB24等图像像素数据
javacpp-ffmpeg系列: javacpp-FFmpeg系列之1:视频拉流解码成YUVJ420P,并保存为jpg图片 javacpp-FFmpeg系列之2:通用拉流解码器,支持视频拉流解码并转 ...
- bzoj 4671 异或图 —— 容斥+斯特林反演+线性基
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4671 首先,考虑容斥,就是设 \( t[i] \) 表示至少有 \( i \) 个连通块的方 ...
- POJ3159(最短路)
Candies Time Limit: 1500MS Memory Limit: 131072K Total Submissions: 27051 Accepted: 7454 Descrip ...
- 'xxx' declared `static' but never defined
'xxx' declared `static' but never defined [问题描述] uart.c文件中有函数read_sample的实现: [plain] view plain copy ...