1. synchronized

If two threads are using the same function( here we use output to print out string) of another instance, if we want to make sure that these two threads are not disturbing each other.
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.

The calling function must be the same one from the same instance!
 Error Example 1:
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.

ANSWER 1:
we can make it possible by letting two threads calling for the
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: 

Since we already know the key point is to make the same Instance be synchronized, so we can make the two threads call fordifferent functions( output1,
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

If the method is a static method, since static method is initialized before Instance, if we still want to synchronize two method, One way is to make both of the two methodstatic synchronized, another way, we can synchronize on the instance's
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

when we have many threads working together, sometimes we need to switch between each other on some condition. such as thread1 work 5 times, then switch to thread 2 to run 10 times, then switch back to thread1 to run 5 times. On this condition, we need
to design the logic, so that the thread knowns when to run, and when to wait aside and let others to run.
1. The detailed work of thread can be written to different methods into a single Class, and all these method should add Synchronized key word. So that when we Initialize the class, all the threads that want to do such
work, are synchronized on one lock and will wait for their turn.
2. Condition of switching to each other should also be written into this class, so that other classes can be robust. can it's easy to maintain the code latter.
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的更多相关文章

  1. Java Thread系列(五)synchronized

    Java Thread系列(五)synchronized synchronized锁重入 关键字 synchronized 拥有锁重入的功能,也就是在使用 synchronized 时,当线程等到一个 ...

  2. multi thread for Java

    I try to do a testing for HashTable Sychronized behavior today. As an Sychronized Object, HashTable ...

  3. 多线程学习三:Thread API,ThreadLocal,synchronized,volatile和Condition

    一.Thread API: setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) 首先要了解什么是Thread. ...

  4. java 多线程实现四种方式解析Thread,Runnable,Callable,ServiceExcutor,Synchronized ,ReentrantLock

    1.Thread实现: import java.util.Date; import java.text.SimpleDateFormat; public class MyThread extends ...

  5. Multi account chang login with multi -thread

    void worker_DoWork(object sender, DoWorkEventArgs e) { isBussy = true; if (Common.isChangingAccount) ...

  6. python multi process multi thread

    muti thread: python threading: https://docs.python.org/2/library/threading.html#thread-objects https ...

  7. Individual Project - Word frequency program - Multi Thread And Optimization

    作业说明详见:http://www.cnblogs.com/jiel/p/3978727.html 一.开始写代码前的规划: 1.尝试用C#来写,之前没有学过C#,所以打算先花1天的时间学习C# 2. ...

  8. Makefile 的 prequisite 執行順序 single multi thread

    Makefile 代碼如下: B 需要 A 的 產出, all: A B A B 是 target, case 1: single-thread make -j1 則執行的順序為 A -> B ...

  9. Java Thread 的使用

    Java Thread 的使用 Java Thread 的 run() 与 start() 的区别 Java Thread 的 sleep() 和 wait() 的区别   一.线程的状态 在正式学习 ...

  10. Java并发编程:Thread类的使用

    Java并发编程:Thread类的使用 在前面2篇文章分别讲到了线程和进程的由来.以及如何在Java中怎么创建线程和进程.今天我们来学习一下Thread类,在学习Thread类之前,先介绍与线程相关知 ...

随机推荐

  1. 软件测试作业——WordCount的测试

    一.代码提交 1.代码地址:https://gitee.com/zst1978805482/WordCount 2.作业地址:https://edu.cnblogs.com/campus/xnsy/T ...

  2. Source Insight 4.0的使用(转)

    原作者地址:https://blog.csdn.net/qq_39660930/article/details/77499455 一.项目管理 1.新建一个项目 快捷键Alt+Shift+N可以打开新 ...

  3. Yii2 hasMany 关联后加条件

    当前模型类为活动表id,关联评论表的type_id,条件是评论表的type要等于2public function getComment(){ return $this->hasMany(Comm ...

  4. java中构造函数的特点

    构造函数的名字必须和类名完全相同,构造函数不能有 返回值,就是void 也不要写,构造函数不可以被子类继承 构造函数可以重载但是不可以被子类覆盖. 简单的例子 class A{ A(){ } A(in ...

  5. Beam编程系列之Apache Beam WordCount Examples(MinimalWordCount example、WordCount example、Debugging WordCount example、WindowedWordCount example)(官网的推荐步骤)

    不多说,直接上干货! https://beam.apache.org/get-started/wordcount-example/ 来自官网的: The WordCount examples demo ...

  6. Linux 上安装 weblogic12C (静默安装) (一)

    最近负责在linux上安装weblogic,客户说要安装最新的版本,版本号为 12.1.X(12.1.2,12.1.3).开始以为和旧版安装一样,使用控制台的方式,下载bin文件,然后一步步在cons ...

  7. Linux Tomcat 80端口 Port 80 required by Tomcat v8.5 Server at localhost is already in use.

    Port 80 required by Tomcat v8.5 Server at localhost is already in use. The server may already be run ...

  8. 【IP】Linux中检测IP地址冲突

    在Windows系统中,如果本地网络IP地址出现冲突,会出现图标提示. 在Linux系统中,并没有提供相关的功能,如果本地网络采用静态IP地址配置,出现比较奇怪的网络连接问题,如ssh连接复位,可以考 ...

  9. C# 自定义属性Attribute

    自定义属性 /// <summary> /// 脱敏属性 /// </summary> public class SensitiveAttribute:Attribute { ...

  10. SpringSecurity 3.2入门(9)自定义权限控制代码实现

    1. 一个自定义的filter,必须包含authenticationManager,accessDecisionManager,securityMetadataSource三个属性,我们的所有控制将在 ...