namespace { // strand提供串行执行, 能够保证线程安全, 同时被post或dispatch的方法, 不会被并发的执行. // io_service不能保证线程安全 boost::asio::io_service m_service; boost::asio::strand m_strand(m_service); boost::mutex m_mutex; void print(int id) { // boost::mutex::scoped_lock lock(m_mutex); static int count = 0; PRINT_DEBUG("id: " << boost::lexical_cast<std::string>(id)); PRINT_DEBUG("count: " << boost::lexical_cast<std::string>(++count)); } void ioRun1() { while(true) { m_service.run(); } } void ioRun2() { while(true) { m_service.run(); } } void strand_print1() { // PRINT_DEBUG("Enter print1"); m_strand.dispatch(boost::bind(print, 1)); // PRINT_DEBUG("Exit print1"); } void strand_print2() { // PRINT_DEBUG("Enter print2"); m_strand.post(boost::bind(print, 2)); // PRINT_DEBUG("Exit print2"); } void strand_print3() { // PRINT_DEBUG("Enter print3"); m_strand.post(boost::bind(print, 3)); // PRINT_DEBUG("Exit print3"); } void strand_print4() { // PRINT_DEBUG("Enter print4"); m_strand.post(boost::bind(print, 4)); // PRINT_DEBUG("Exit print4"); } // 将上面的m_strand换成m_service后, void service_print1() { // PRINT_DEBUG("Enter print1"); m_service.dispatch(boost::bind(print, 1)); // PRINT_DEBUG("Exit print1"); } void service_print2() { // PRINT_DEBUG("Enter print2"); m_service.post(boost::bind(print, 2)); // PRINT_DEBUG("Exit print2"); } void service_print3() { // PRINT_DEBUG("Enter print3"); m_service.post(boost::bind(print, 3)); // PRINT_DEBUG("Exit print3"); } void service_print4() { // PRINT_DEBUG("Enter print4"); m_service.post(boost::bind(print, 4)); // PRINT_DEBUG("Exit print4"); } } void test_strand() { boost::thread ios1(ioRun1); boost::thread ios2(ioRun2); boost::thread t1(strand_print1); boost::thread t2(strand_print2); boost::thread t3(strand_print3); boost::thread t4(strand_print4); t1.join(); t2.join(); t3.join(); t4.join(); m_service.run(); } void test_service() { boost::thread ios1(ioRun1); boost::thread ios2(ioRun2); boost::thread t1(service_print1); boost::thread t2(service_print2); boost::thread t3(service_print3); boost::thread t4(service_print4); t1.join(); t2.join(); t3.join(); t4.join(); m_service.run(); }test_strand的执行结果:
2013-01-05 17:25:34 626 [8228] DEBUG - id: 4 2013-01-05 17:25:34 631 [8228] DEBUG - count: 1 2013-01-05 17:25:34 634 [5692] DEBUG - id: 1 2013-01-05 17:25:34 637 [5692] DEBUG - count: 2 2013-01-05 17:25:34 640 [5692] DEBUG - id: 2 2013-01-05 17:25:34 642 [5692] DEBUG - count: 3 2013-01-05 17:25:34 646 [5692] DEBUG - id: 3 2013-01-05 17:25:34 649 [5692] DEBUG - count: 4test_ioserivice的执行结果:
2013-01-05 17:26:28 071 [3236] DEBUG - id: 1 2013-01-05 17:26:28 071 [5768] DEBUG - id: 2 2013-01-05 17:26:28 071 [5108] DEBUG - id: 3 2013-01-05 17:26:28 076 [3236] DEBUG - count: 1 2013-01-05 17:26:28 079 [5768] DEBUG - count: 2 2013-01-05 17:26:28 083 [5108] DEBUG - count: 3 2013-01-05 17:26:28 087 [3236] DEBUG - id: 4 2013-01-05 17:26:28 099 [3236] DEBUG - count: 4从结果可以看到, 在test_strand中print中两个打印函数成对执行, 在test_ioservice两个打印函数就没有线程安全可言了.
如果要保证test_ioservice同步, 就要加上mutex, 在代码中被注释的那句.
1.为什么需要ModelDriven?
所谓ModelDriven,意思是直接把实体类当成页面数据的收集对象。比如,有实体类User如下:
package cn.com.leadfar.struts2.actions;
public class User {
private int id;
private String username;
private String password;
private int age;
private String address;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
假如要写一个Action,用来添加User。
第一种做法是直接在Action中定义所有需要的属性,然后在JSP中直接用属性名称来提交数据:
UserAction:
public class UserAction {
private int id;
private String username;
private String password;
private int age;
private String address;
public String add(){
User user = new User();
user.setId(id);
user.setUsername(username);
user.setPassword(password);
user.setAge(age);
user.setAddress(address);
new UserManager().addUser(user);
return "success";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
add_input.jsp:
<form action="test/user.action" method="post">
<input type="hidden" name="method:add">
username:<input type="text" name="username"> <br/>
password:<input type="text" name="password"> <br/>
age:<input type="text" name="age"> <br/>
address:<input type="text" name="address"> <br/>
<input type="submit" name="submit" value="添加用户">
</form> <br/>
上述做法不好之处是:如果实体类的属性非常多,那么Action中也要定义相同的属性。
第二种做法是将User对象定义到UserAction中,然后在JSP中通过user属性来给user赋值:
UserAction:
public class UserAction {
private User user;
public String add(){
new UserManager().addUser(user);
return "success";
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
add_input.jsp:
<form action="test/user.action" method="post">
<input type="hidden" name="method:add">
username:<input type="text" name="user.username"> <br/>
password:<input type="text" name="user.password"> <br/>
age:<input type="text" name="user.age"> <br/>
address:<input type="text" name="user.address"> <br/>
<input type="submit" name="submit" value="添加用户">
</form> <br/>
这种做法不好的地方是:JSP页面上表单域中的命名变得太长
第三种做法是利用ModelDriven机制,让UserAction实现一个ModelDriven接口,同时实现接口中的方法:getModel()。如下所示:
public class UserAction implements ModelDriven{
private User user;
@Override
public Object getModel() {
if(user == null){
user = new User();
}
return user;
}
public String add(){
new UserManager().addUser(user);
return "success";
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
JSP的代码如下:
<form action="test/user.action" method="post">
<input type="hidden" name="method:add">
username:<input type="text" name="username"> <br/>
password:<input type="text" name="password"> <br/>
age:<input type="text" name="age"> <br/>
<input type="submit" name="submit" value="添加用户">
</form> <br/>
可见,第三种做法是比较好的,Action和JSP写起来都比较简单。
2.ModelDriven背后的机制?
ModelDriven背后的机制就是ValueStack。界面通过:username/age/address这样的名称,就能够被直接赋值给user对象,这证明user对象正是ValueStack中的一个root对象!
那么,为什么user对象会在ValueStack中呢?它是什么时候被压入ValueStack的呢?答案是:ModelDrivenInterceptor(关于Interceptor的概念,请参考后续章节的说明)。ModelDrivenInterceptor是缺省的拦截器链的一部分,当一个请求经过ModelDrivenInterceptor的时候,在这个拦截器中,会判断当前要调用的Action对象是否实现了ModelDriven接口,如果实现了这个接口,则调用getModel()方法,并把返回值(本例是返回user对象)压入ValueStack。
请看ModelDrivenInterceptor的代码:
public class ModelDrivenInterceptor extends AbstractInterceptor {
protected boolean refreshModelBeforeResult = false;
public void setRefreshModelBeforeResult(boolean val) {
this.refreshModelBeforeResult =
<Window x:Class="WpfApp2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:objs="clr-namespace:WpfApp2.Objects" xmlns:col="clr-namespace:System.Collections;assembly=mscorlib" xmlns:sys="clr-namespace:System;assembly=mscorlib" Title="MainWindow" Height="300" Width="300"> <Window.Resources> <col:ArrayList x:Key="ds"> <objs:Student Name="Timothy" Skill="WPF" HasJob="True" Id="1"/> <objs:Student Name="Anders" Skill="C#" HasJob="True" Id="2"/> <objs:Student Name="Tommy" Skill="ASP.NET" HasJob="True" Id="3"/> <objs:Student Name="Jim" Skill="WCF" HasJob="True" Id="4"/> <objs:Student Name="Andy" Skill="WF" HasJob="False" Id="5"/> <objs:Student Name="Jack" Skill="JAVA" HasJob="True" Id="6"/> </col:ArrayList> <Style TargetType="{x:Type TextBlock}"> <Setter Property="Width" Value="60"/> </Style> <DataTemplate x:Key="nameDT" DataType="{x:Type objs:Student}"> <TextBox x:Name="textBoxName" Width="60" Text="{Binding Name}" GotFocus="textBoxName_GotFocus"/> </DataTemplate> <DataTemplate x:Key="skillDT"> <TextBox x:Name="textBoxSkill" Width="60" Text="{Binding Skill}"/> </DataTemplate> <DataTemplate x:Key="hasJobDT"> <CheckBox Width="60" IsChecked="{Binding HasJob}"/> </DataTemplate> </Window.Resources> <StackPanel> <ListView x:Name="lv" ItemsSource="{StaticResource ds}"> <ListView.View> <GridView> <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Id}"/> <GridViewColumn Header="姓名" CellTemplate="{StaticResource nameDT}"/> <GridViewColumn Header="技术" CellTemplate="{StaticResource skillDT}"/> <GridViewColumn Header="已工作" CellTemplate="{StaticResource hasJobDT}"/> </GridView> </ListView.View> </ListView> <Button Content="Find" Margin="5,5" Click="Button_Click" Width="80"/> </StackPanel> </Window>
private void textBoxName_GotFocus(object sender, RoutedEventArgs e) { TextBox tb = e.OriginalSource as TextBox; ContentPresenter cp = tb.TemplatedParent as ContentPresenter; Student stu = cp.Content as Student; this.lv.SelectedItem = stu; ListViewItem lvi = this.lv.ItemContainerGenerator.ContainerFromItem(stu) as ListViewItem; CheckBox cb = FindVisualChild<CheckBox>(lvi); MessageBox.Show(cb.IsChecked.ToString()); } public ChildType FindVisualChild<ChildType>(DependencyObject obj) where ChildType:DependencyObject { //借助VisualTreeHelper类获取子控件 for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject child = VisualTreeHelper.GetChild(obj, i); if (child != null && child is ChildType) return child as ChildType; else { ChildType childOfChild = FindVisualChild<ChildType>(child); if (childOfChild != null) return childOfChild; } } return null; }
11.5 深入浅出话Style
构成Style最重要的两种元素是Setter和Trigger,Setter类帮助我们设置控件的静态外观风格,Trigger类则帮助我们设置控件的行为风格。
11.5.1 Style中的Setter
<Window x:Class="WpfApp3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Style TargetType="{x:Type TextBlock}"> <Setter Property="FontSize" Value="24"/> <Setter Property="TextDecorations" Value="Underline"/> <Setter Property="FontStyle" Value="Italic"/> </Style> </Window.Resources> <Grid> <StackPanel> <TextBlock Text="Hello WPF!"/> <TextBlock Text="This is a sample Style!"/> <TextBlock Text="by Anders 1/5/13" Style="{x:Null}"/> </StackPanel> </Grid> </Window>
11.5.2 Style中的Trigger
1. 基本Trigger
<Window x:Class="WpfApp3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Style TargetType="{x:Type CheckBox}"> <Style.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter Property="FontSize" Value="24"/> <Setter Property="Foreground" Value="Orange"/> </Trigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <StackPanel> <CheckBox Content="月光宝盒" IsChecked="True"/> <CheckBox Content="大话西游" IsChecked="False"/> </StackPanel> </Grid> </Window>
2. MultiTrigger
MultiTrigger实际上叫MultiConditionTrigger更合适,因为必须多个条件同时成立时才会被触发。
<Window x:Class="WpfApp3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Style TargetType="{x:Type CheckBox}"> <Style.Triggers> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsChecked" Value="True"/> <Condition Property="Content" Value="大话西游"/> </MultiTrigger.Conditions> <Setter Property="FontSize" Value="24"/> <Setter Property="Foreground" Value="Orange"/> </MultiTrigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <StackPanel> <CheckBox Content="月光宝盒" IsChecked="True"/> <CheckBox Content="大话西游" IsChecked="True"/> <CheckBox Content="大话西游" IsChecked="False"/> <CheckBox Content="月光宝盒" IsChecked="True"/> </StackPanel> </Grid> </Window>