在现代的程序开发中,多线程是必不可少的,熟练使用多线程能够极大的提高项目并发,本篇文章我们就来看看一些多线程编程案例。
例1:
package com.kelin1314; public class TestObject { private String name; private boolean flag = true; public TestObject(String name) { this.name = name; } public synchronized String getName() { try { System.out.println("begin get"); while (!flag) { wait(); } flag = true ? (flag = false) : (flag = true); System.out.println("over get"); notify(); } catch (Exception e) { e.printStackTrace(); } return name; } // public synchronized static void setName(String name) { public synchronized void setName(String name) { try { System.out.println("begin set"); while (flag) { wait(); } flag = true ? (flag = false) : (flag = true); System.out.println("over set"); notify(); } catch (Exception e) { e.printStackTrace(); } } } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - package com.kelin1314; /** * This thread is used to test the variable scope of key word "synchronized". * * @author Administrator * */ public class TestThreadOne extends Thread { private TestObject object; public TestThreadOne(TestObject object) { this.object = object; } @Override public void run() { while (true) { object.getName(); } } } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- package com.kelin1314; public class TestThreadTwo extends Thread { private TestObject object; public TestThreadTwo(TestObject object) { this.object = object; } @Override public void run() { while (true) { object.setName("two"); } } } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - package com.kelin1314; public class Main { /** * @param args */ public static void main(String[] args) { TestObject object = new TestObject("object"); TestThreadOne testThreadOne = new TestThreadOne(object); TestThreadTwo testThreadTwo = new TestThreadTwo(object); testThreadOne.start(); testThreadTwo.start(); } }
例2:
from threading import Thread msg_l = [] format_l = [] def talk(): while True: msg = input('>>: ') .strip() if not msg: continue msg_l.append(msg) def format_msg(): while True: if msg_l: res = msg_l.pop() format_l.append(res.upper()) def save(): while True: if format_l: with open('db.txt', 'a', encoding = 'utf-8') as f: res = format_l.pop() f.write('%s\n' % res) if __name__ == '__main__': t1 = Thread(target = talk) t2 = Thread(target = format_msg) t3 = Thread(target = save) t1.start() t2.start() t3.start()
以上就是本篇文章的所有内容,更多java经典实例内容可以关注奇Q工具网了解详情。
推荐阅读: