In this paper, we investigate the joint optimal sensing and distributed Medium Access Control (MAC) protocol design problem for cognitive radio (CR) networks. We consider both scenarios with single and multiple channels. For each scenario, we design a synchronized MAC protocol for dynamic spectrum sharing among multiple secondary users (SUs), which incorporates spectrum sensing for protecting active primary users (PUs). We perform saturation throughput analysis for the corresponding proposed MAC protocols that explicitly capture the spectrum-sensing performance. Then, we find their optimal configuration by formulating throughput maximization problems subject to detection probability constraints for PUs. In particular, the optimal solution of the optimization problem returns the required sensing time for PUs' protection and optimal contention window to maximize the total throughput of the secondary network. Finally, numerical results are presented to illustrate developed theoretical findings in this paper and significant performance gains of the optimal sensing and protocol configuration.