Multi-Thread 1: how to use synchronized
1. synchronized
public class TraditionalThreadSynchronize {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new TraditionalThreadSynchronize().initial();
}
private void initial(){
final Outputter outputter = new Outputter();
new Thread(new Runnable(){ //this is the first theread
public void run(){
while(true){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputter.output("aaaaaaaaaaa"); //the thread want to use outputer print a string.
}
}
}).start();
new Thread(new Runnable(){//thread two
public void run(){
while(true){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputter.output("bbbbbbbbbbbbb"); //thread two also want to use the function to print
}
}
}).start();
}
class Outputter{
public void output(String name){
int len = name.length();
for(int i= 0;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
If code won't escape disturbing each other.
new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new outputer.output("bbbbbbbb");
}
}
}).start();
if we use new outputer.output("bbbbbbbbb"), still won't work. since the two threads are calling different function from two different instance.So one thing is clear that we have to add synchronized key word and it should
be added to the same Instance.
same function, of the same Instance so we can change the output function to:
public synchronized void output(String name){
int len = name.length();
for(int i=0;i<len;i++){
<span style="white-space:pre"> </span>System.out.print(name.charAt(i));
}
System.out.println();
}
// Synchronized add to the function is the same as synchronized(this). the Instance is sychronized for this function
ANSWER 2:
and output3), as long as the instance is synchronized(which is also easy to do: both of the two functions should addsynchronized
key word)
public void output(String name){
int len = name.length();
synchronized (this)
{
for(int i=0;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}
public synchronized void output2(String name){
int len = name.length();
for(int i=0;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
ANSWER 3: in the case that the function is a static method
class
public void output(String name){
int len = name.length();
synchronized (Outputer.class)
{
for(int i=0;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}
public synchronized void output2(String name){
int len = name.length();
for(int i=0;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
2.Threads communicate with each other
to design the logic, so that the thread knowns when to run, and when to wait aside and let others to run.
work, are synchronized on one lock and will wait for their turn.
public class Business {
boolean subFirst = true;
public synchronized void subJob(){
while(!subFirst){
try {
this.wait(); //even though get the lock, if it's not our turn, we should wait and give back the lock.
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i=0;i<10;i++){
System.out.println("sub...."+Thread.currentThread().getName()+" is running "+(i+1));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
subFirst = false;
this.notify(); // wake other waitting threads
}
public synchronized void mainjob(){
while(subFirst){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i=0;i<100;i++){
System.out.println("main*****"+Thread.currentThread().getName()+" is running "+(i+1));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
subFirst = true;
this.notify();
}
}
Main class
public class TraditionalThreadCommunication {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TraditionalThreadCommunication t = new TraditionalThreadCommunication();
Business business = new Business();
t.startJob(business,50);
}
public void startJob(final Business business, final int cycles){
new Thread(new Runnable(){ //sub thread run
public void run(){
//the detail logic should all be written into Business class
for(int i=1; i<=cycles;i++)
business.subJob();
}
}).start();
new Thread(new Runnable(){ //main thread run
public void run(){
//the detail logic should be written in business class, so that the
//this class be robust, and can be easily changed in latter maintainance
for(int i=1; i<=cycles;i++)
business.mainjob();
}
}).start();
}
}
Multi-Thread 1: how to use synchronized的更多相关文章
- Java Thread系列(五)synchronized
Java Thread系列(五)synchronized synchronized锁重入 关键字 synchronized 拥有锁重入的功能,也就是在使用 synchronized 时,当线程等到一个 ...
- multi thread for Java
I try to do a testing for HashTable Sychronized behavior today. As an Sychronized Object, HashTable ...
- 多线程学习三:Thread API,ThreadLocal,synchronized,volatile和Condition
一.Thread API: setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) 首先要了解什么是Thread. ...
- java 多线程实现四种方式解析Thread,Runnable,Callable,ServiceExcutor,Synchronized ,ReentrantLock
1.Thread实现: import java.util.Date; import java.text.SimpleDateFormat; public class MyThread extends ...
- Multi account chang login with multi -thread
void worker_DoWork(object sender, DoWorkEventArgs e) { isBussy = true; if (Common.isChangingAccount) ...
- python multi process multi thread
muti thread: python threading: https://docs.python.org/2/library/threading.html#thread-objects https ...
- Individual Project - Word frequency program - Multi Thread And Optimization
作业说明详见:http://www.cnblogs.com/jiel/p/3978727.html 一.开始写代码前的规划: 1.尝试用C#来写,之前没有学过C#,所以打算先花1天的时间学习C# 2. ...
- Makefile 的 prequisite 執行順序 single multi thread
Makefile 代碼如下: B 需要 A 的 產出, all: A B A B 是 target, case 1: single-thread make -j1 則執行的順序為 A -> B ...
- Java Thread 的使用
Java Thread 的使用 Java Thread 的 run() 与 start() 的区别 Java Thread 的 sleep() 和 wait() 的区别 一.线程的状态 在正式学习 ...
- Java并发编程:Thread类的使用
Java并发编程:Thread类的使用 在前面2篇文章分别讲到了线程和进程的由来.以及如何在Java中怎么创建线程和进程.今天我们来学习一下Thread类,在学习Thread类之前,先介绍与线程相关知 ...
随机推荐
- mysql - VARCHAR与VHAR的区别
一, 基本介绍 char 和 varchar 两类型类似, 用来存储字符串,不同之处来自于他们的保存和检索的差别, char 属于固定的长度字符类型, 而varchar 属于可变长度的字符类型 值 C ...
- 如何透过上层div点击下层的元素解决方法
一.问题描述 笔者是在些一个登录界面时遇到这个问题的,需求是点击登录按钮出现登录悬浮框,初始化时登录悬浮框是display:none的,但笔者发现登录框那一块区域的input框无法响应点击时间,也无法 ...
- Immutable-不变模式与不变类
不变模式的定义 一个对象在创建之后就不再变化,就是所谓的不变模式(Immutable Pattern): 一般来讲,一个对象要么就是可变对象(Mutable Object),要么就是不变模式(Immu ...
- Android中的ListView点击时的背景颜色设置
想设置listview中每行在点击.选中等不同状态下有不同的背景颜色,或者背景图片. 这可以用Android的Selector来实现.它可以定义组件在不同状态下的显示方式. 新建一个xml文件list ...
- 2.3 js基础--DOM
一.javascript组成 ECMAScript:核心解释器[为我们提供好了最基本的功能:变量声明.函数.语法.运算]. 兼容性:完全兼容. DoM:文档对象 ...
- 白话SpringCloud | 第六章:Hystrix监控面板及数据聚合(Turbine)
前言 前面一章,我们讲解了如何整合Hystrix.而在实际情况下,使用了Hystrix的同时,还会对其进行实时的数据监控,反馈各类指标数据.今天我们就将讲解下Hystrix Dashboard和Tur ...
- POST 还是 GET?
POST 还是 GET? 浏览器使用 method 属性设置的方法将表单中的数据传送给服务器进行处理.共有两种方法:POST 方法和 GET 方法. 如果采用 POST 方法,浏览器将会按照下面两步来 ...
- asp.net FileUpload上传文件夹并检测所有子文件
1.在FileUpload控件添加一个属性 webkitdirectory=""就可以上传文件夹了 <asp:FileUpload ID="FileUpload1& ...
- 数据库中存放着HTML并附带样式,如何在界面上对已有的样式进行修改
在工作中遇到这样一个问题,数据库中存放着HTML代码,并且还带有样式,我要在界面上修改他已经写好的样式,例如把这个字段的字体改成微软雅黑,数据库中对应字段内容如下图 在界面面上是直接把上图这段HTML ...
- 如何查询日志文件中的所有ip,正则表达式
IPV4必须满足以下四条规则: 1.任何一个1位或2位数字,即0-99: 2.任何一个以1开头的3位数字,即100-199: 3.任何一个以2开头.第2位数字是0-4之间的3位数字,即200-249: ...