多线程论文

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

一.线程的创建:

1.

2.

3.

二.T imer传统定时器:

1.

2.

三.线程互斥技术synchronized:

1.线程安全问题可以用银行转账问题解释。

2.

static class Outputer{

public void output(String name){

int len = name.length();

synchronized (Outputer.this){

for(int i=0;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

System.out.print(name.charAt(i));

}

System.out.println();

}

public static synchronized void output3(String name){

int len = name.length();

for(int i=0;i

System.out.print(name.charAt(i));

}

System.out.println();

}

}

四.线程同步问题:

例题:子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着又回到主线程循环100次,如此循环50次,请写出程序。

代码:

new TraditionalThreadCommunication().init();

}

public void init(){

final Business business = new Business();

new Thread(new Runnable() {

@Override

public void run() {

for(int i=1;i<=50;i++){

business.sub(i);

}

}

}).start();

for(int i=1;i<=50;i++){

business.main(i);

}

}

class Business{

private boolean bShouldSub= true;

public synchronized void sub(int i) {

while (!bShouldSub){

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

for(int j=1;j<=10;j++){

System.out.println("sub Thread sequece "+j+",loop of "+i); }

bShouldSub= false;

this.notify();//唤醒主线程

}

public synchronized void main(int i){

while(bShouldSub){

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

经验:

1.要用到共同数据(包括同步锁)的若干个方法应该归在同一个类身上,这种设计设

计正好体现了高类聚和程序的健壮性。

2.互斥上锁不是写在线程上的代码,而是要写在线程要访问的资源类内部的!!!

五.线程范围内的共享变量

1. HashMap存取各个线程之间的变量来区分各个线程。

2.

3.ThreadLocal方法:

将上面的HashMap改为:

Private static ThreadLocal x = new ThreadLocal(); 4.总结:一个ThreadLocal代表一个变量,所以里面只能放一个数据,当有两个变量时,就要定义两个ThreadLocal;但是当变量过大时,就要先将变量封装到类里面,再将这个类放到ThreadLocal中。

5.类中包装:

六.多个线程访问共享对象和数据的方式:

1.如果每一个线程执行的代码相同,则可以使用同一个Runnable对象,这个Runnable

对象中有那个共享数据(例如:卖票)

1.例题:设计4个线程,其中两个线程每次对j加1,两外两个线程每次对j减1,写出

程序:

2.

public class MultiThreadShareData {

private int count=100;

public static void main(String[] args) {

MultiThreadShareData md = new MultiThreadShareData();

Inc ic = md.new Inc();

Dec dc = md.new Dec();

for(int i=0;i<2;i++){

new Thread(ic).start();

new Thread(dc).start();

}

}

private synchronized void inc(){

count++;

System.out.println(Thread.currentThread().getName()+" -inc(): " + count);

}

private synchronized void dec(){

count--;

System.out.println(Thread.currentThread().getName()+" -dec(): " + count);

}

class Inc implements Runnable {

@Override

public void run() {

while (true){

inc();

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

class Dec implements Runnable {

@Override

public void run() {

while (true){

相关文档
最新文档